How to attach external js to Drupal.behaviours

by Ahmad   Last Updated August 01, 2020 01:07 AM

If we write js code in Drupal.behaviours like below

(function($) {
  Drupal.behaviors.my_module = {
    attach : function(context, settings) {

}
};
})(jQuery);

that code will be execute multiple times on a page if needed even after an ajax callback.

But in the preprocess_node I have added an external js file. The problem is on node page there is a view with an ajax pager. When I move to next page through views ajax pager(views infinite pager) then that external js did not work.

So my question is, Is there a way to add the external js to Drupal.behaviours?

Tags : 7 javascript


Answers 2


You can use .once available in Drupal.

Drupal.behaviors.Newsletter = {
    attach: function (context, settings) {
      $('#cd-sso-newsletter-form').once('form-Newsletter', function () {
        // Your Code.

        });
      });
    }
  };
NTT
NTT
October 03, 2016 15:45 PM

Normally external libraries add functionality to the website but you have to code some JS to make it work. But sometimes, the library also executes something automatically if you add a specific class to a HTML tag. And this is what must be happening to you.

You are adding the external library and it is being executed in your HTML tags that are rendered from the beginning, but not in those that are added later through ajax.

But it shouldn't be a problem for you to execute the library function again for your specific new items in a custom Drupal.behaviors function. The external JS library is already loaded, so you just have to add its functionality to the new item in the way:

    (function($) {
      Drupal.behaviors.my_module = {
        attach : function(context, settings) {
           $(".my_new_item_selector").once('to-be-executed-once', function () {
             $(this).externalLibraryFunction();
           });
        }
      };
    })(jQuery);
juankvillegas
juankvillegas
October 03, 2016 16:42 PM

Related Questions


Use drupal.settings variables on javascript

Updated March 27, 2015 14:18 PM

Passing Javascript variable in my module file

Updated July 27, 2015 14:03 PM

Remove jquery script

Updated April 20, 2015 21:03 PM

Calling a contact form in a certain page

Updated August 23, 2015 17:03 PM