Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Prevent duplicate JavaScript event handlers in Drupal 8

Parent Feed: 

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.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web