Search code examples
javascriptjqueryhtmljquery-hoverjquery-click-event

Javascript/JQuery function not triggered after .load


When a user clicks the "search" button in my ASP.NET application, a temporary "spinner" div is loaded. Then when the search (finally) completes, the contents of the spinner div are replaced by the HTML returned by the SubmitSearch method.

$("#spinner").load("@Url.Action("SubmitSearch","Search")");

I also have this JavaScript file that is loaded in:

$(document).ready(function() {
    $(".card--result").hover(function () {
        alert("hover");
        $(this).css('cursor', 'pointer');
    });

    $(".card--result").click(function() {
        var url = $(this).attr('data-url');
        window.open(url, "_self");
    });
});

However, the problem is that a div with card--result class is part of the new HTML that gets added to the page after the .load method succeeds.

How can I register the .hover and .click functions so that they are actually triggered on the newly loaded HTML elements?


Solution

  • You need event delegation for this.

    Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

    $(document).on("click", ".card--result", function() {
       var url = $(this).attr('data-url');
       window.open(url, "_self");
    });
    

    and for the cursor part I guess CSS would be enough

    .card--result {
       cursor: pointer;
    }