My question is about how jQuery finds various DOM nodes that don’t exist until they are loaded by AJAX.
My particular issue is that my jQueryUI tabs() script only works if it is included together with the tabs div on the page fragment loaded by AJAX. This script doesn’t work if was loaded as part of the original main template page before the tabs div exists (i.e., before being ajax loaded).
To explain what I mean here’s some simple code description:
$('a.ajax').live('click', function(){
$.ajax({ url: '/get_page_with_tabs',
success: function(data){
$('div#ajax').append(data); // the content that gets replaced
}
});
});
$('div#tabs').tabs();
// this script must be part of the "data" along with the <div id="tabs></div>
// it can't be loaded along with the main template page which contains: <div id="ajax"> </div> and the $.ajax script
Just one side-note is that I’m actually using PJAX but this appears functionally identical to jQuery AJAX regarding the asynchronous div loading.
how jQuery finds various DOM nodes that don't exist until they are loaded by AJAXIt doesn’t find.
Move the tabs initialization code to the AJAX response handler:
Using
liveandonyou can attach event handlers to elements which do not exist in the page yet (and may be added later by an ajax call orappendsort of function).jQuery can catch these events because of the event “bubbling” – basically, a higher/upper parent catches the child event…