2

I've added a toggle for my superfish menu, it works fine but for every ajax load or colorbox trigger the span is created multiple times. How to fix it???

(function ($){
Drupal.behaviors.customjs  = {
attach: function (context, settings) {
$(document).ready(function(){


$("#superfish-1").before("<span class='toggle'>Menu</span>");
$('#superfish-1').toggle();
 }); 
3

The better way would be to use the context of the behaviour along with .once() as mentioned here ( https://www.drupal.org/node/1667874 ), something like below:

(function ($){
  Drupal.behaviors.customjs  = {
    attach: function (context, settings) {
      // Add context along with .once something like below.
      $("#superfish-1", context).once("CLASS-NAME").before("<span class='toggle'>Menu</span>");
    }
  }
})(jQuery); 
3
  • Damn, I had network failure and my answer got sent after yours. Anyway, +1 from me as we basically did the same thing. I'll leave mine in place, I think it is bit more descriptive.
    – Mołot
    Sep 26 '14 at 8:37
  • @Mołot Yeah please keep yours as well. Sep 26 '14 at 8:40
  • Thanks ankit and @Molot choosing this as the right ans and upvoting Molot's
    – jack
    Sep 27 '14 at 12:58
2

First, don't use $(document).ready in behavior. It should not be needed to make behavior work when things are ready, and second, usually it will be executed immediately if page was ready in the past - not what you want.

Second thing is to always use context in top level $( selectors. And use once() to be sure.

So your code after changes could look like this:

(function ($){
  Drupal.behaviors.customjs  = {
    attach: function (context, settings) {
      $("#superfish-1", context).once("customjs-before").before("<span class='toggle'>Menu</span>");
      $("#superfish-1", context).once("customjs-toggle").toggle();
    }
  };
})(jQuery);
1

Add jQuery once to your menu wrapper http://codekarate.com/blog/drupal-7-prevent-duplicating-javascript-behaviors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.