Reuse modules on the same page and dynamically add a unique ID attribute to each so that you can target it with CSS or JS.

A common problem facing HubSpot developers is figuring out a way to target multiple instances of the same module in order to apply some css or perhaps even manipulate a part of it using javascript. This seems easy enough to do without creating a unique identifier, and in many use cases is unecessary, but instances do exist where knowing how to generate a unique id for a module that is repeated on the same page really comes in handy.

Use Case

There are many but here are a few:

  • Module fields define styles that need to be added to a psuedo-element or an element that cannot be styled inline.
  • JS needs to target each istance of a module in order to do something (common in some js based sliders)
  • Many more!
{# Generating the id is as simple as using the {{name}} tag #}
<section id={{name}} class="generic-module-class">
   {# module does cool stuff here #}

The {{name}} tag will generate a unique name for each instance of the module that is on the page automatically.

Accessing the Dynamic ID

Instead of writing your javascript or css in the module.css or module.js file you will want to move it to the module.html section of your module and wrap it in {% require_css %} or {% require_js %} depending on what you're trying to do with it.

Your new module.html file might look something like this:

<section id={{name}} class="generic-module-class">
   {# module does cool stuff here #}

{# css #}
{% require_css %}
   #{{name}} {
      display: block;
{% end_require_css %}

{# js #}
{% require_js 'footer' %}
document.addEventListener("DOMContentLoaded", function() {
   var module = document.querySelector('#{{name}}');
   // Do things with this instance of module
{% end_require_js %}

The reason why we want to move our css and javascript up to the module.html file is so that we can have access to the hubl {{name}} tag. Hubl is invalid in the module.css and module.js files.

Happy building!