possible to replace window.location.hash?
Asked Answered
D

1

36

I'm wondering whether it's possible to change the hash in window.location.hash and replace it with 'this.id'. Or would I need to change the entire window.location?

Diagnostician answered 31/7, 2010 at 6:49 Comment(0)
R
58

Yes, you can. I do something similar at one of my sites, although with href instead of id, but id works too. A quick example:

$('a[id]').click(function(e)
{
    // This will change the URL fragment. The change is reflected
    // on your browser's address bar as well
    window.location.hash = this.id;
    e.preventDefault();
});
Randolphrandom answered 31/7, 2010 at 6:55 Comment(8)
@jldupont: I should think so.Randolphrandom
@Randolphrandom care to provide a reference to support this?Catchings
I don't have any sources except my own personal experience using it, that's why I said I think so.Randolphrandom
+1: Tested it on: Chrome V25, FF12, Opera 12, all on Linux: it works.Catchings
This actually does not do a replace, it adds an entry to the history.Tiresias
It doesn't replace on chrome for mePhotomicrograph
PLEASE be aware that this adds a history state in IE, regardless of how Chrome handles it.Cordalia
From caniuse.com/#search=location.hash "Supported in effectively all browsers (since IE6+, Firefox 2+, Chrome 1+ etc)"Amplify

© 2022 - 2024 — McMap. All rights reserved.