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

13,195

Solution 1

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.

Solution 2

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.

Share:
13,195
aldona
Author by

aldona

Updated on June 13, 2022

Comments

  • aldona
    aldona almost 2 years

    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.