Skip to content

Instantly share code, notes, and snippets.

@megclaypool
Last active August 19, 2025 18:58
Show Gist options
  • Save megclaypool/71f704ec03e1be6d30bca7039f5ab28a to your computer and use it in GitHub Desktop.
Save megclaypool/71f704ec03e1be6d30bca7039f5ab28a to your computer and use it in GitHub Desktop.

How to structure javascript for Drupal

You need to start with:

((Drupal) => {
  Drupal.behaviors.nameOfLibrary = {
    attach(context) {

Then it ends with:

    },
  };
})(Drupal);

And your custom code goes in the middle. Here's an example:

((Drupal) => {
  Drupal.behaviors.railToggle = {
    attach(context) {
      context
        .querySelectorAll(".rail .component .rail-toggle")
        .forEach((element) => {
          let selector = element.getAttribute("aria-controls");
          let parent = element.parentElement;
          let target = element.parentElement.querySelector(`.${selector}`);
          
          target.setAttribute("aria-hidden", "true");
          parent.setAttribute("aria-expanded", "false");

          element.addEventListener("click", (event) => {
            event.preventDefault();
            target.setAttribute(
              "aria-hidden",
              target.getAttribute("aria-hidden") === "true" ? "false" : "true"
            );
            parent.setAttribute(
              "aria-expanded",
              parent.getAttribute("aria-expanded") === "false"
                ? "true"
                : "false"
            );
          });
        });
    },
  };
})(Drupal);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment