Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ready event not fired on partial page load

Here's the situ: A page which contains html and using the jQuery libray and tabs jQuery UI plugin loads another page when some tab is clicked. The problem is that when the page/html is loaded/rendered (let's simplify this and say it's just doing something like $("#myDiv").load(url);), the ready event is not fired because of course the "window" has already loaded and fired the load event. This means that none of the jQuery things I want to do on load (partial load) of the page are executed. The UI.tabs plugin is designed to load pages into other tabs and we can assume that other pages may contain their own jQuery... so there should be some way around this..

I can think of very horrible ways to get over the problem, like have a script block at the bottom of the page being rendered (loaded into a div) which does all things I would do when ready is fired (as you can assume the browser has rendered the page already if the script block is hit). This however is VERY bad practise. Any suggestions?

like image 743
Mr AH Avatar asked Dec 09 '09 17:12

Mr AH


3 Answers

How are you firing the AJAX request to the server? If you're using ASP.NET AJAX, then Brian Hasden's answer is what you are looking for. If you are using jQuery to send the request, then you can either set a call back using the load function.

$(".ajaxLink").load(url, null, function() {
    // code here
});

load() Documentation

or set a global ajaxComplete event that is fired every time an ajax call is complete.

$(document).ajaxComplete(function() {
    // code here
});

ajaxComplete() Documentation

like image 101
Kyle Trauberman Avatar answered Sep 30 '22 04:09

Kyle Trauberman


The load method offers a callback which is executed after the content has been loaded.

$("#myDiv").load(url, null, function() { 
   //do your stuff here 
});

Full documentation and examples at jQuery.com: http://docs.jquery.com/Ajax/load

like image 33
mkedobbs Avatar answered Sep 30 '22 05:09

mkedobbs


OK.. so i have a simple answer to this problem now, which should mean minimal code changes. Rather than the sub views (these are real aspx views which have no html, head or body tags) having a js include (essentially the client side behaviour model) which responds to $(document).ready, we can use the suggestion from mkedobbs to provide something similar. Simply:

$("#MyDiv").load("page.htm", null, function(){ $(document).trigger("PartialLoaded"); });

Then in the sub view js include

$(document).bind("PartialLoaded", function(){ .........});
like image 28
Mr AH Avatar answered Sep 30 '22 05:09

Mr AH