Main menu

How to stop Drupal javascript behavior from executing several times

Published by dnovikov on Tue, 03/12/2013 - 17:23

Recently, during a new PopupAd module development, I've ran into a strange trap with Drupal Behaviors attach function. It executed infinite number of times:

(function ($) {

Drupal.behaviors.initPopupAd = {
  attach: function (context, settings) {
    if (!$.isFunction($.colorbox)) {
      return;
    }
   
    var popupad_settings = settings.popupad;
   
    setTimeout(function() {
      $.colorbox(popupad_settings);
    }, popupad_settings.delay);
  }
}

})(jQuery);

After playing back and forth with jQuery once method, I ended up with applying it to HTML body selector:

(function ($) {

Drupal.behaviors.initPopupAd = {
  attach: function (context, settings) {
    if (!$.isFunction($.colorbox)) {
      return;
    }
   
    $('body', context).once('popupad', function() {
      var popupad_settings = settings.popupad;
   
      setTimeout(function() {
        $.colorbox(popupad_settings);
      }, popupad_settings.delay);
    });
  }
}

})(jQuery);

 

That did a trick for me.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.