0

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?

0

You can use .once available in Drupal.

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

        });
      });
    }
  };
4
  • How will I add my external js file here in this code?
    – Ahmad
    Oct 4 '16 at 7:32
  • You have to add external JS file using drupal_add_js function in a module or inc file
    – NTT
    Oct 4 '16 at 8:03
  • I have added the external js file using that function but the problem is it does not gets loaded after ajax.
    – Ahmad
    Oct 4 '16 at 8:14
  • You can use api.jquery.com/jquery.getscript
    – NTT
    Oct 4 '16 at 8:19
0

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);
2
  • I have to just call this function? or I have to include that external js file but how?
    – Ahmad
    Oct 4 '16 at 7:30
  • @Ahmad your JS file is already included, isn't it? Oct 4 '16 at 14:34

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.