0

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();
        }
      }
    }
  }
};

1 Answer 1

0

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.

7
  • Well, my original post was edited. I am using drupal 7. I tried the above code, and it wont work. Reason - I have this class "'.node-' + nid" multiple times... Mar 25, 2018 at 6:29
  • So what are the conditions that it should execute under?
    – Jaypan
    Mar 25, 2018 at 6:30
  • As soon as the DOM is ready, the JS should execute, and not even once after that. I have multiple AJAX calls on the page, some automated, some on some events. The JS should not fire, post the AJAX events. Mar 26, 2018 at 7:40
  • Have you got more than one div.search-result on the page?
    – Jaypan
    Mar 26, 2018 at 7:43
  • Yes, each search result div has this class. Mar 27, 2018 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.