Detect change in hash value of URL using JavaScript

javascript, jquery

Solution

You can listen to the `hashchange` event:

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

Problem

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.

Original source

Related problems