views:

20

answers:

3

I'm creating a script that allows me to launch pop-in windows based on the URL's hashtag. I'm able to get it to work when the user plugs in the URL+hash directly in the location bar. However, when the anchor links are clicked, the script doesn't seem to perform the .load() function. Is my sequencing wrong, or am I going about this the completely wrong way?

<script>
$(document).ready(function() {
var loc = window.location.hash;
var container = $('.container');
 if ( loc == "#content1" ) { $('.container').load('content1.html') }
 if ( loc == "#content2" ) { $('.container').load('content2.html') }
});
</script> 
<body> 

<ul class="navigation"> 
<li><a href="#content1">Launch content1</a></li> 
<li><a href="#content2">Launch content2</a></li> 
</ul> 

<div class="container"></div> 

</body>
A: 

You will need to either make a function to call or use window.location or something to that effect to get what you want. Your jQuery code only runs right after the page is loaded, and just clicking those links does not reload the page.

Badger
A: 

Your script is only going to run when the page first loads. When clicking on anchor that contains a hash fragment, the page will not reload, so your script in $(document).ready... will not run again.

I think you want to add the jQuery Hashchange event plugin: http://benalman.com/projects/jquery-hashchange-plugin/

Then you can bind actions to the hashchange event, which will execute a callback when the user changes the hash fragment by clicking your links. Your script will end up looking something like:

$(window).bind('hashchange', function() {
 pageCaller();
});

function pageCaller() {
 var loc = window.location.hash;
 var container = $('.container');
 if ( loc == "#content1" ) { $('.container').load('content1.html') }
 if ( loc == "#content2" ) { $('.container').load('content2.html') }
}

pageCaller();
hundredwatt
Thanks, that totally worked! (I posted a condensed version using a function to make it cleaner in a comment to myself.)
Marc P
Edited mine to include your DRYer code. Glad I could help!
hundredwatt
A: 

Thanks @hundredwatt, the plugin totally worked! I condensed the code further with some function() action:

$(window).bind('hashchange', function() {
 pageCaller();
});

function pageCaller() {
 var loc = window.location.hash;
 var container = $('.container');
 if ( loc == "#content1" ) { $('.container').load('content1.html') }
 if ( loc == "#content2" ) { $('.container').load('content2.html') }
}

pageCaller();
Marc P