Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect change in hash value of URL using JavaScript

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.

like image 347
user115422 Avatar asked Feb 20 '13 01:02

user115422


People also ask

How do I know if my URL has been changed?

You can use the popstate method to detect those URL changes and make UI changes as needed. window. addEventListener('popstate', function (event) { // The URL changed... }); Yesterday, we learned that the first property passed into the history.

How do I change the URL of a hash?

hash = '#food'; This will replace the URL's hash with the value you set for it. If you wish the change the hash within the URL when the user clicks an anchor tag, why not just use <a href="#bar">Foo</a> ?

What is Onhashchange?

The onhashchange event occurs when there has been changes to the anchor part (begins with a '#' symbol) of the current URL. An example of what an anchor part actually is: Assume that the current URL is. http://www.example.com/test.htm#part2 - The anchor part of this URL would be #part2.


2 Answers

You can listen to the hashchange event:

$(window).on('hashchange',function(){      $('h1').text(location.hash.slice(1)); }); 
like image 55
undefined Avatar answered Oct 02 '22 20:10

undefined


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/

like image 32
Brad Christie Avatar answered Oct 02 '22 18:10

Brad Christie