views:

329

answers:

4

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.

+3  A: 

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.

David Dorward
+1  A: 

When you click the link, code will be executed in the following order:

  • jQuery click-handlers
  • onclick-handlers
  • native/default behavior (calling the link, writing it to window.location)

I would recommend that you use this.href instead. Also use e.preventDefault() so the native/default behavior isn't performed by the browser.

Marcel J.
A: 

Since the default event changing the location.hash hasn't happened yet, you can fetch the .hash from the anchor directly instead, like this:

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

Though, since the image is the only thing, you can attach the handler to the <a> itself, like this:

$("a").click(function() { 
  $("#displayFile").load('files/'+ this.hash +'.html').fadeIn(300);  
});  
Nick Craver
A: 

Thank you guys! Works like charm. I decided to use this.parentNode.hash way.

By the way - can I give you reputation somehow, vote "good answer" etc. or everything goes automatically here?

Thx.

aldona
You accept an answer via the check-mark beside the answer that resolved the issue :)
Nick Craver