tags:

views:

59

answers:

4

Hi,

I have some elements on my page that get loaded via an ajax call. I'd like to make the url in the user's browser change when they click an item. For example, my page has a list of animals:

Horse
Cow
Pig

when the user clicks one of those items, I want to update the url in their browser's address bar (not reload the page):

http://www.mysite.com#Horse
http://www.mysite.com#Cow
http://www.mysite.com#Pig

I think that's allowed, putting the # symbol in the address without reloading the page. Is there a way to do this in jquery?

Thanks

+6  A: 

You can do it in vanilla JS, no need for jQuery using location.hash, like this:

window.location.hash = "Cow";
Nick Craver
Note that `.hash` is one part of the `.url` for the page.
Loadmaster
Cool thanks that works great.
@Loadmaster - `.href`, perhaps? I don't think `.url` works in browsers I've tried.
Matchu
Eeesh, yep, you're right.
Loadmaster
+2  A: 

Can't you have the element linked to the hash?

<a href="#Pig">Pig</a>
a.feng
+1  A: 

Be warned! window.location.hash is not implemented in every browser! A fix for this would look like:

if (!("hash" in window.location)) {
  window.location.__defineGetter__("hash", function() {
    if (location.href.indexOf("#") == -1) return "";
    return location.href.substring(location.href.indexOf("#"));
  });
  window.location.__defineSetter__("hash", function(v) {
    if (location.href.indexOf("#") == -1)
      location.href += v;
    location.href = location.href.substring(0, location.href.indexOf("#")) + v;
  });
}

This is untested, so test it first! My advice would be to use:

<a href="#Pig">Oink!</a>

to change urls. (By the way, the behavior of window.location.hash that is implemented here is the same you expect with browsers that implement it. You have to add the hash character to the url.)

Tim
This is news to me...out of curiosity, which browser doesn't support it?
Nick Craver
Hmmm... I remember not getting support in some browser or another... Or it was the fact that it was inconsistent between them... I forget. I remember I had to do this for one of my projects 'cause it wasn't there...
Tim
A: 

I'd look into using SWFAddress for deep-linking .... it works the same in JavaScript as ActionScript

Michael