user10728458
user10728458

Reputation:

Is there a jQuery event listener for jQuery's .load();?

I want to run a $(document).ready(); type of function when a div element loads, but it should run after I use jQuery's .load().

I'm making a website where I want to navigate between pages by having a container where my page is loaded. When I load a page, I say myContainer.empty(); to clear it, and then I have a separate html file which contains the html for the other page, so then I just say myContainer.load('myOtherPage.html');. This works perfectly, but I need an event listener to run when a certain page gets loaded into myContainer.

I use:

myPageContainer.empty();
myPageContainer.load('home.html');

but, my javascript doesn't pick up the fact that it loaded, and I have some events that need firing when the page gets loaded.

So, in short, I basically need a type of event listener that runs when my page gets loaded via jQuery's .load();.

Upvotes: 0

Views: 1537

Answers (1)

Jaapaap
Jaapaap

Reputation: 221

$("#success").load("somefile.html", function(response, status, xhr){
  if(status == "error"){
    var msg = "Sorry but there was an error: ";
    $("#error").html( msg + xhr.status + " " + xhr.statusText );
  }
});

See documentation

enter image description here

@Sebastian's comment :

if (myPageContainer.addEventListener) {
  myPageContainer.addEventListener('load', function() {
       /* do stuff */ 
  });
} else {
  // it's IE!
  myPageContainer.attachEvent('load', function() {
    /* do stuff */
  });
}

Hope this works for you?

Upvotes: 5

Related Questions