1

I have a form that uses ['#attached']['js'] to attach a simple javascript file. A checkbox element of this same form uses ['#ajax'] to dynamically update some portions of the form. I'm finding that, when the form is rebuilt after the ajax callback, the javascript file is reattached multiple times, causing unintended behaviors.

Is there any way to avoid reattaching a javascript file to a form if that same javascript has been attached previously?

  • 4
    That would usually be solved using once() in the javascript file itself. – Clive Dec 15 '17 at 16:19
4

As Clive mentioned, the usual way to solve this is to use once() when attaching behaviors:

Drupal.behaviors.myBehavior = {
  attach: function (context, serverSettings) {
    $('elementSelector', context).once('myId', function () {
      // The code that will be executed only once.
    });
  }
};

Also, check the official docs on Managing JavaScript in Drupal 7.

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.