Duplicate event

Prevent duplicate JavaScript event handlers in Drupal 8

Drupal behaviors documentation suggests that we use the "once" method to prevent binding JavaScript event handlers multiple times on Ajax requests.

Prevent multiple binding of JavaScript event handlers

If you use event listener functions in Drupal behaviors, use .once() function to avoid duplicate handlers after running Ajax requests.

In this example, clicking on a button element toggles a paragraph, and it will work well if you don't run any Ajax requests on the same page. But if you do, Drupal.behaviors will run again on the button and click listener will be added multiple times. Consequently the paragraph will be toggled multiple times.

Drupal.behaviors.ws_custom = {
    attach: function (context, settings) {
      $('button').click(function() {
        $("p").toggle();
      });
    }
  };

Since Drupal integrates the jQuery Once plugin in its core since Drupal 7, to prevent the paragraph to toggle multiple times simply change your code to this:

Drupal.behaviors.ws_custom = {
    attach: function (context, settings) {
      $('button').once().click(function() {
        $("p").toggle();
      });
    }
  };

Now, click listener will be added only once to the element button and you will prevent duplicating JavaScript in behaviors.

Alternative solution

Another way to solve this problem is to run the unbind function before adding event listener function to the element. For example:

Drupal.behaviors.ws_custom = {
    attach: function (context, settings) {
      $('button').unbind("click");
      $('button').click(function() {
        $("p").toggle();
      });
    }
  };

If you have another examples, leave them in the comments below.

To see more about writing jQuery in Drupal and using Drupal behaviors click here.

Share this post