This is my first Drupal 8 project and I'm running into a problem figuring out how to attach an extra event handler to an object. I am working on a custom theme using Radix as base theme. I am using Superfish as menu module. One of the issues is that Superfish creates an extra 'root' menu called 'Menu' that is shown when the Bootstrap hamburger menu is clicked. You subsequently need to click on 'Menu' to show the actual (accordion) menu. I found a snippet of code in an issue: https://www.drupal.org/project/superfish/issues/2891228 that hides the 'Menu' toggle, but I cannot get it to work.

I have setup a library definition and created a 'script.js':

import "popper.js";
import "bootstrap";

(function($, Drupal) {
  Drupal.behaviors.helloWorld = {
    attach(context) {
      console.log("Hello World");

  Drupal.behaviors.myMainMenu = {
    attach(context) {
      console.log("myMainMenu: " + context.toString());
      $(".navbar-collapse", context).once('myMainMenu').on(
        "show shown shown.bs.collapse show.bs.collapse",
        () => {
        if (!$("#superfish-main-accordion").hasClass("sf-expanded")) {
          console.log('no expand');
})(jQuery, Drupal);

I know the script runs, because I see 'Hello World' and 'myMainMenu' + some glob several times in the console. But I never manage to get the other console messages.

I also know the code in the if statement is correct, because, if I run it manually in the console, it works as intended.

What should be the correct code?

1 Answer 1


Couple of problems. But the main two are:

  1. In Drupal 8, you need to call $.each() on $.once()
  2. In Drupal you don't need to call $.on() on elements. The combination of Drupal.behaviors and $.once() achieves the same goal.

So your code should be something like:

$(".navbar-collapse", context).once('myMainMenu').each(function () {
  // Do stuff here
  • I get your point, but this doesn't achieve the desired result. I.e. the 'Menu' root menu-item should be hidden and the rest of the menu expanded. Is there another way to attach an event listener to a specific event?
    – hepabolu
    Commented Jul 26, 2019 at 20:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.