How do I avoid behaviors are invoked after an AJAX call?

by Vaibhav Jain   Last Updated October 19, 2019 06:07 AM - source

I have a search result page, with the first set of data being fetched during the page load, and we add a Load More button. Clicking on this button fires an AJAX call, using the ajax_links_api module. After the AJAX call is completed, we append more search results to the current set. I have a behavior where I read the URL parameter; if it exists, I open a Colorbox.

If the colorbox opens on page load, we close it, and then click on Load More (which fires AJAX); then the Colorbox JavaScript is fired again, and we see the popup in action again.

I don't want to fire the Colorbox JavaScript after AJAX is completed/fired.

I tried jQuery Once, but it didn't work.

How can I achieve this? Can I detect when an AJAX call happens?

The following is the code I am using.

Drupal.behaviors.openColorbox = {
  attach: function (context, settings) {
    if ($('body', context).hasClass('page-search-site')) {
      var nid = url('?node');
      if (nid != undefined) {
        if (nid.trim()) {
          $('div.search-result')
            .find('.node-' + nid)
            .once('colorbox-clicked')
            .click();
        }
      }
    }
  }
};


Answers 1


You are using .once in the wrong spot

(function($, Drupal) {

  "use strict";

  function openColorbox(context) {
    $(context).find("div.search-result").once("openColorbox").each(function () {
      if ($('body', context).hasClass('page-search-site')) {
        var nid = url('?node');
        if (nid != undefined) {
          if (nid.trim()) {
            $('div.search-result')
              .find('.node-' + nid)
              .click();
          }
        }
      }
    }
  }

  Drupal.behaviors.openColorbox = {
    attach: function (context) {
      openColorbox(context);
    }
  };

}(jQuery, Drupal));

Note that this is D8 style. If you are using D7, the above will not work as it is done differently, and you didn't tell us which Drupal version you are using.

Jaypan
Jaypan
March 24, 2018 00:34 AM

Related Questions


Extends Drupal AJAX autocomplete behaviours

Updated October 30, 2017 04:07 AM

Drupal 8 search run runs script. How to disable it?

Updated April 18, 2018 13:07 PM


Drupal URL Arguments in Javascript

Updated May 01, 2015 21:03 PM