Trigger an action when a given hash is found in the URL

8

The idea is to start an animation when a given hash is found in the URL.

Example

Taking the example of a page whose navigation works by hash:

<nav>
  <ul>
    <li><a href="#john">John</a></li>
    <li><a href="#doe">Doe</a></li>
    <li><a href="#Jane">Jane</a></li>
  </ul>
</nav>

<section id="john">Super BuBu</section>
<section id="doe">Super Saiyan</section>
<section id="jane">Jane Porter</section>

The user clicks the menu and the page scrolls to the id in question. The idea is to trigger an action when for example accessing the #doe that could be performed through the click event on the link with href equal to #doe .

Problem

If the user directly accesses the page through a URL that already contains the hash to direct it to the correct section, the action previously associated with clicking on the referenced element is not triggered.

http://www.meusite.com/bananas.php#doe

Question

How do I trigger an action when a hash is found in the browser URL?

    
asked by anonymous 15.01.2014 / 02:46

2 answers

4

If the problem is "what to do when the page already opens with the hash present," I suggest making the method that would handle the click more generic, and invoke it right after the page is loaded:

$(function() {

    var acoes = {
        "#hash1": function() { ... },
        "#hash2": function() { ... },
        ...
    };

    function executarAcao() {
        if ( window.location.hash && acoes[window.location.hash] )
            acoes[window.location.hash]();
    }

    $("a").filter(function() {
        return ($(this).attr("href") || "").indexOf("#") == 0;
    }).click(function(e) {
        e.preventDefault();
        window.location.hash = $(this).attr("href");
        executarAcao();
    });

    ...

    // No final do seu script
    executarAcao();
});
    
15.01.2014 / 03:25
3

You can monitor the event hashchange :

window.onhashchange = function() {
    alert(window.location.hash);
};

Example in JSFiddle

Within the function you can check the hash and act accordingly.

Details:
If I'm not mistaken, between Firefox and Chrome, one of the two triggers (hehe) the event hashchange automatically when the page loads, and in the other event the event needs to be triggered manually. And IE only supports this event from version 8, and also does not trigger the event when the page loads.

Then we recommend calling window.onhashchange() as soon as the DOM loads, to get the effect you want.

    
15.01.2014 / 03:13