Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with single page websites and maintaining state using a URL hash and jQuery

Tags:

jquery

url

hash

I'm working on my portfolio, making it entirely jQuery based. So my problem is when you go to a page, then refresh then it will take you to the home page again. So I have two questions, actually.

  1. How do you (via jQuery/Javascript) get a "hash code" from the url?
    1. E.G. I want the bold part of this: http://portfolio.theadamgaskins.com/Portfolio/#graphicsDesign
  2. How do you change the url in the address bar when you navigate to a new page to contain the hash code for that page?
    1. E.G. when you go the the graphicsDesign page, the link in the address bar changes to http://portfolio.theadamgaskins.com/Portfolio/#graphicsDesign
like image 581
Entity Avatar asked Nov 06 '10 14:11

Entity


3 Answers

You make the anchor point to an internal link like so:

<a href="#graphicsDesign">Graphics</a>

And then simply make jQuery respond to the click event and let the browser follow the internal link naturally. The browser should now have the internal link in it's address bar. You can use the following JavaScript to parse the URL and then load the correct part of the HTML document. You will need to write the code so that the correct content is loaded based off what the browsers internal address is.

if(window.location.hash === "graphicsDesign" ||
window.location.hash === "somethingElse") {
    loadContent(window.location.hash);
}
like image 152
Sam152 Avatar answered Jan 01 '23 08:01

Sam152


The jQuery BBQ ("Back Button & Query") plugin is quite good as well. http://benalman.com/projects/jquery-bbq-plugin/

like image 34
leppert Avatar answered Jan 01 '23 07:01

leppert


Use one of the many history plugins available, e.g. here: http://plugins.jquery.com/project/jquery-history-web-2-0-hashchange-history-remote

like image 30
Jonas Høgh Avatar answered Jan 01 '23 08:01

Jonas Høgh