JavaScript and Drupal

DrupalTM Blog

Welcome to our Drupal blog! Stay up to date with the latest Drupal news, best practices, and techniques.

1. How should modules implement JavaScript in Drupal 9 and 10?

Drupal recommends modules to attach JavaScript logic using Drupal.behaviors. For instance, the code below demonstrates this approach:

(function ($, Drupal) {
  'use strict';

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
        $(this).next('ul').toggle('show');
      });
    }
  };

})(jQuery, Drupal);

2. When does Drupal call attached behaviors, and what parameters are passed?

Drupal core calls attached behaviors when the DOM is fully loaded. It passes two arguments: context (representing the DOM) and settings (containing server-side injected settings).

3. How is Drupal.attachBehaviors() called and when does it occur in Drupal 9 and 10?

Drupal.attachBehaviors() is called to attach all behaviors and is typically triggered after the DOM is loaded using $(document).ready().

(function ($, Drupal) {
  'use strict';

  // Attach all behaviors.
  $(document).ready(function () {
    Drupal.attachBehaviors(document, Drupal.settings);
  });

})(jQuery, Drupal);

 

4. How can behaviors be made efficient and run only once in Drupal 9 and 10?

To ensure behaviors run only once, developers can utilize jQuery.once().

(function ($, Drupal) {
  'use strict';

  Drupal.behaviors.syfyGlobalHideMenu = {
    attach: function (context, settings) {
      $('.nav-flyout', context).once('remove-modals').each(function () {
        $(document).keyup(function (e) {
          if (e.keyCode == 27) {
            $(this).removeClass('js-flyout-active');
          }
        });
      });
    }
  };

})(jQuery, Drupal);

5. Why is considering the context variable important in Drupal 9 and 10 behaviors?

The context variable contains the affected piece of HTML, and using it in jQuery selectors is crucial for efficient code.

(function ($, Drupal) {
  'use strict';

  Drupal.behaviors.syfyGlobalHideMenu = {
    attach: function (context, settings) {
      $(document, context).keyup(function (e) {
        if (e.keyCode == 27) {
          $('.nav-flyout', context).removeClass('js-flyout-active');
        }
      });
    }
  };

})(jQuery, Drupal);

 

These examples demonstrate how to adapt JavaScript code for Drupal 9 and 10, considering best practices and maintaining compatibility with these versions while addressing common questions about CMS and JavaScript integrationpt.