0

The following in a Drupal behaviour is working fine:

  $('.trigger', context).click(function(e){
    e.preventDefault();
    $('.target').toggleClass('open');
  });

However I know that I should be using the once function. Is the following correct? It does work but so did the code above so im not sure how to check if its been done with best practices.

  $('.trigger', context).once('toggle-name', function(){
    $(this).click(function(e) {
      e.preventDefault();
      $('.target').toggleClass('open');
    });
  });
0

If you don't use .once() then your code will still work but - depending on whatever else happens on the page - your click() function may be attached multiple times to the same element, which is less efficient and may cause undesired effects if, as in this case, you are using a toggle function in your callback.

Because you are limiting the scope of your selector by context, multiple attachment is less likely, but you should definitely use once() if you want your code to be robust.

  • I understand the general concept. Is my second block of code correct? – Evanss Nov 4 '15 at 17:38
  • Looks OK to me, yes. – Alfred Armstrong Nov 4 '15 at 17:38

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.