Skip to content

Instantly share code, notes, and snippets.

@rmorse
Last active December 8, 2022 22:16
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rmorse/b157004c68870dbd9fb9 to your computer and use it in GitHub Desktop.
Save rmorse/b157004c68870dbd9fb9 to your computer and use it in GitHub Desktop.
Search & Filter Pro - Ajax Events
//detects the start of an ajax request being made
$(document).on("sf:ajaxstart", ".searchandfilter", function(){
console.log("ajax start");
});
//detects when the ajax request has finished and the content has been updated
// - add scripts that apply to your results here
$(document).on("sf:ajaxfinish", ".searchandfilter", function(){
console.log("ajax complete");
//so load your lightbox or JS scripts here again
});
//an event fired when S&F is initialised and S&F scripts have been loaded
$(document).on("sf:init", ".searchandfilter", function(){
console.log("S&F JS initialised");
});
//depending on where you add your JS, sometimes its necessary to wrap the above events in a function (as is standard practice):
(function ( $ ) {
"use strict";
$(document).on("sf:init", ".searchandfilter", function(){
console.log("S&F JS initialised");
});
}(jQuery));
@garyMelican
Copy link

So glad you're addressing this issue.

Google analytics isn't capturing my site's Ajax URL changes - https://trendfriend.io/trends

This code isn't working either sadly, any idea why it may not be?

Thanks Ross

@regiside
Copy link

Thanks for this! Helped me out.

@Christopher-Hayes
Copy link

Very helpful, thanks for sharing this. In my case, I was able to use this to update a category URL param when the user selects a new S&F category.

    // Detect ajax requests from the user selecting a new category and update URL with new category param
    jQuery(document).on('sf:ajaxfinish', '.searchandfilter', () => {
        // Get newly selected category
        const newCategoryInput = jQuery('.sf-option-active input');

        // Update URL
        const urlParams = new URLSearchParams(window.location.search);
        urlParams.set('category', newCategoryInput.val());
        const newPath = `${window.location.pathname}?${urlParams}`;

        // Prevent refresh; Stop browser history from saving each category
        if (window.history.replaceState) {
           window.history.replaceState({}, null, newPath);
        }
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment