Search code examples
htmlloadexternaljqueryjquery-on

How do I trigger a function to execute after external HTML is loaded?


JS:

$(document).ready(function(){

    $("#loader").load("external.html");

    $("#buttonClickText").live('click', function() {
        $("#buttonClickText").text("Text changed after button click.");
    });

    // MYSTERY FUNCTION
    $("#pageLoadText").text("Text changed after external HTML was loaded.");
    //

});

External HTML:

<div id="buttonClickText">
    This text changes when clicked.
</div>

<div id="pageLoadText">
    This text should have changed when external HTML was loaded, but didn't.
</div>

Main HTML (just showing the relevant tag):

<div id="loader"></div>

Also, I know .live() is deprecated for jQuery 1.7+, I'm guessing the solution will be similar using .on()

Thanks!


Solution

  • from http://api.jquery.com/load/:

    This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched element to the returned data.

    Just pass a function as the second argument.

    $('#result').load('ajax/test.html', function() {
      alert('Load was performed.');
    });