Scope JavaScript to a specific module instance

Hi, HubSpot’s HubL templating language has a special tag {% scope_css %}…{% end_scope_css %} to scope CSS to a specific module instance. Is there a {% scope_js %} or {% scope_script %} for JavaScript.
I’m looking to make this code so that it specific to the module. So that if I use multiple versions of the module on the same page the JavaScript wont effect the other modules. Thanks

function Tabs() {
 var bindAll = function() {
 var menuElements = document.querySelectorAll('[data-tab]');
 for(var i = 0; i < menuElements.length ; i++) {
 menuElements[i].addEventListener('click', change, false);
 }
 }

 var clear = function() {
 var menuElements = document.querySelectorAll('[data-tab]');
 for(var i = 0; i < menuElements.length ; i++) {
 menuElements[i].classList.remove('active');
 var id = menuElements[i].getAttribute('data-tab');
 document.getElementById(id).classList.remove('active');
 }
 }

 var change = function(e) {
 clear();
 e.target.classList.add('active');
 var id = e.currentTarget.getAttribute('data-tab');
 document.getElementById(id).classList.add('active');
 }

 bindAll();
}

var connectTabs = new Tabs();

Use a {{ name }} tag in your html and your js. That’s effectively the same as scoping.

So something like

<div id="{{ name }}">
<div data-tab="1"></div>
<div data-tan="2"></div>
</div>

 function Tabs(containerId) {
 var container = document.getElementById(containerId);

 var bindAll = function() {
 var menuElements = container.querySelectorAll('[data-tab]');

etc.

var connectTabs = new Tabs('{{ name }}');

You’ll may need to adjust the rest of your js accordingly but that’s the basis idea to scope it.
{{ name }} outputs the unique identifier for the instance of the module.


Barry Grennan

Freelance HubSpot CMS Developer

Website | Contact | LinkedIn