What is Drupal Behavior?

By manoj , 15 March, 2025

In Drupal, Behaviors are a way to attach JavaScript functionality to elements on a page. Behaviors are part of Drupal's JavaScript API and are designed to work seamlessly with Drupal's rendering and caching system. They ensure that JavaScript is executed when content is added to the page, either during the initial page load or when new content is added dynamically (e.g., via AJAX).

Key features of Drupal Behaviors:

  1. Reusability: Behaviors can be attached to elements multiple times without causing conflicts.
  2. Dynamic Content: They are re-executed when new content is added to the page (e.g., via AJAX).
  3. Encapsulation: Behaviors are scoped to specific elements, preventing global namespace pollution.

How to Implement Drupal Behaviors in Drupal 11

To implement Drupal Behaviors in Drupal 11, follow these steps:

1. Create a Custom JavaScript File

Create a JavaScript file in your custom module or theme. For example, if you're working in a custom module, place the file in:

>

modules/custom/my_module/js/my_behavior.js

2. Define the Behavior

In your JavaScript file, define the behavior using the Drupal.behaviors object. Each behavior should be a property of this object.

// my_behavior.js
(function (Drupal, once) {
  'use strict';
  // Define the behavior.
  Drupal.behaviors.myCustomBehavior = {
    attach: function (context, settings) {
      // Use 'once' to ensure the behavior is applied only once per element.
      once('myCustomBehavior', '.my-selector', context).forEach(function (element) {
        // Add your JavaScript logic here.
        element.addEventListener('click', function () {
          alert('Element clicked!');
        });
      });
    },
    detach: function (context, settings, trigger) {
      // Optional: Clean up when elements are removed from the DOM.
      if (trigger === 'unload') {
        // Remove event listeners or perform other cleanup tasks.
      }
    }
  };
})(Drupal, once);

3. Attach the JavaScript File

Attach the JavaScript file to your module or theme using a library.

In a Module:

Create a my_module.libraries.yml file in your module:

my_custom_behavior:
  version: 1.x
  js:
    js/my_behavior.js: {}
  dependencies:
    - core/drupal
    - core/once

Attach the library in your module's hook_page_attachments() or hook_preprocess_HOOK():

// my_module.module
function my_module_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'my_module/my_custom_behavior';
}

In a Theme:

Create a my_theme.libraries.yml file in your theme:

my_custom_behavior:
  version: 1.x
  js:
    js/my_behavior.js: {}
  dependencies:
    - core/drupal
    - core/once

Attach the library in your theme's THEME_NAME.info.yml file:

libraries:
  - my_theme/my_custom_behavior

4. Use the once Function

The once function ensures that your behavior is applied only once to each element, even if the behavior is re-executed (e.g., after an AJAX request). This is a Drupal core utility and is the recommended way to handle behaviors.

5. Test Your Behavior

  • Clear the cache (drush cr or via the Drupal UI).
  • Load the page and verify that your JavaScript behavior works as expected.
  • Test with dynamic content (e.g., AJAX-loaded content) to ensure the behavior is re-applied correctly.

Example Use Case

Suppose you want to add a click event to all elements with the class .my-button. Here's how you would implement it:

// my_behavior.js
(function (Drupal, once) {
  'use strict';
  Drupal.behaviors.myButtonBehavior = {
    attach: function (context, settings) {
      once('myButtonBehavior', '.my-button', context).forEach(function (button) {
        button.addEventListener('click', function () {
          console.log('Button clicked!');
        });
      });
    }
  };
})(Drupal, once);

Key Points to Remember

  1. Use once: Always use the once function to ensure your behavior is applied only once per element.
  2. Attach Libraries Properly: Ensure your JavaScript file is attached via a library in your module or theme.
  3. Dynamic Content: Behaviors are re-executed when new content is added to the page, so ensure your code handles this gracefully.
  4. Dependencies: Include core/drupal and core/once as dependencies in your library.