PDA

View Full Version : Run jQuery code after DOM is loaded



delvec28
16 Dec 2009, 02:52 PM
I have a website design where I want the header and navigation bar to stay loaded on the screen, and not need to reload each time a new page is opened. If I click any tab on the navigation bar, this is the piece of javascript that is executed to load the clicked URL in a given div container.


$("#navbar > ul > li > a").click(function(event){
event.preventDefault();
var thisURL = $(this).attr("href");
$(".container").load(thisURL);
});

Now I have found a minor problem with this - I have an accordion menu powered by jQuery on the 'about.html' page. In the head of the html, I include the following:


<script type="text/javascript">
$(document).ready(function(){
$("#accordion-menu").accordion({collapsible: true, active: false, autoHeight: false});
});
</script>

When I type in www.myurl.com/about, the menu is loaded fine. But if I open a separate page, say for instance the home page, and then click on the about navigation tab, the jQuery does not run.

I'm assuming this is because the document.ready function is only run once the initial page is loaded, and does not fire when the $(".container").load(thisURL) line is executed. I have found a workaround where I run the jQuery accordion call in the body of the about.html page, and not the head of the document. With that said, though, is there a way to do this with all the jQuery in the head of the document? I tried to put the jQuery accordion call within a load event of the containing div, but this did not work.

Thanks for the help!

jam3v
28 Dec 2009, 10:50 AM
Try this:

http://docs.jquery.com/Events/live