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?
Asked
Active
Viewed 4.6k times
1 Answers
57
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();
});

BoltClock
- 700,868
- 160
- 1,392
- 1,356
-
@jldupont: I should think so. – BoltClock Apr 05 '13 at 17:18
-
1@BoltClock care to provide a reference to support this? – jldupont Apr 05 '13 at 17:18
-
2I don't have any sources except my own personal experience using it, that's why I said I *think* so. – BoltClock Apr 05 '13 at 17:19
-
1+1: Tested it on: Chrome V25, FF12, Opera 12, all on Linux: it works. – jldupont Apr 05 '13 at 17:23
-
This actually does not do a replace, it adds an entry to the history. – Manuel Fahndrich Oct 02 '13 at 21:29
-
1It doesn't replace on chrome for me – Liron Harel Nov 28 '13 at 15:43
-
PLEASE be aware that this adds a history state in IE, regardless of how Chrome handles it. – verism Nov 10 '14 at 15:06
-
From https://caniuse.com/#search=location.hash "Supported in effectively all browsers (since IE6+, Firefox 2+, Chrome 1+ etc)" – Vigrant Dec 11 '18 at 21:51