jqueryjquery-migrate

Reactivate code after filter is used


I am not very known with jQuery in combination with jQuery Migrate. The site I am working on uses jQuery 1.12 with Migrate version 1.4.1

After some searching the below script works fine at page load:

jQuery(".single_add_to_cart_button").click(function(e) {
    e.preventDefault();
    var url = jQuery(this).data('href');
    window.open(url, '_blank');
    return false;
});

But after some filter build the old fashioned way, this listener is 'forgotten'.

What to do?


Solution

  • You are removing the element, where the listener is attached to. This happens probably at the filtering time. You can circumvent that behavior, if you set the listener on a parent element, which is not being removed at all (e.g. in a <td> the <table> element). I would not set the listener at the top level (document), because it is much more performing to set it on a parent, which is not being removed. If you set the listener to the document, every click is being watched and searched for the .single_add_to_cart_button element.

    You can set the listener to the parent, but only reacting to clicks on .single_add_to_cart_button if you use the following snippet:

    jQuery("#tableWithId").on("click", ".single_add_to_cart_button", function(e) {
        e.preventDefault();
        var url = jQuery(this).data('href');
        window.open(url, '_blank');
        return false;
    });