jQuery "window.location.hash" - getting hash too late?

aldona picture aldona · Aug 19, 2010 · Viewed 13.1k times · Source

I'm working on some script but it have a serious problem with hashes.

I have a list of link-images like:

<a href="#1"><img src="1.jpg" /></a>
<a href="#1"><img src="2.jpg" /></a>
<a href="#1"><img src="3.jpg" /></a>

All I want to do is to load file files/#1.html after clicking the first image, files/#2.html after the second etc.

Here's my jQuery function:

$("a img").click(
function()
{  
        var hash = window.location.hash;
        $("#displayFile").load('files/'+ hash +'.html');
        $("#displayFile ").fadeIn(300);  
 });  

So when I click a image it should add hash to the url (href="#1"), load the right file to #displayFile div and fade it in.

But actually when I click the image it shows empty #displayFile div and after i refresh the site with the same hash it loads the content. I believe the script gets the hash long before it's in URL.

How to fix it?

Thanks.

Answer

Quentin picture Quentin · Aug 19, 2010

Event handlers run before default actions. Short of nasty tricks involving setTimeout you can't get the link to be followed before the function completes.

Read this.href instead.

That said, it sounds like you are using arbitrary fragment identifiers instead of URIs to sensible things. If so: I'd fix up the href so it points to a real URL that loads the image. Build on things that work.