Detect change in hash value of URL using JavaScript

47,306

Solution 1

You can listen to the hashchange event:

$(window).on('hashchange',function(){ 
    $('h1').text(location.hash.slice(1));
});

Solution 2

personally, I'd use sammy which gives you the flexibility to template the hashtag (add placeholders and be able to read them back). e.g.

<script src="/path/to/jquery.js"></script>
<script src="/path/to/sammy.js"></script>
<script>
  $(function(){
      // Use sammy to detect hash changes
      $.sammy(function(){
          // bind to #:page where :page can be some value
          // we're expecting and can be retrieved with this.params
          this.get('#:page',function(){
              // load some page using ajax in to an simple container
              $('#container').load('/partial/'+this.params['page']+'.html');
          });
      }).run();
  });
</script>

<a href="#foo">Load foo.html</a>
<a href="#bar">Load bar.html</a>

An example can be found here: http://jsfiddle.net/KZknm/1/

Share:
47,306
user115422
Author by

user115422

Updated on May 09, 2020

Comments

  • user115422
    user115422 about 4 years

    I'm working on a simple application which is single page based (due to project restrictions) and has dynamic content. I understand the dynamic content alright but what I don't understand is how to set-up a script that changes the html of a div when the hash value in the URL changes.

    I need a JavaScript script to work as such:

    Url: http://foo.com/foo.html div contents: <h1>Hello World</h1>

    Url: http://foo.com/foo.html#foo div contents: <h1>Foo</h1>

    How would this work?

    Please help! Thanks.