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.
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.
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> ?
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.
You can listen to the hashchange
event:
$(window).on('hashchange',function(){ $('h1').text(location.hash.slice(1)); });
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With