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?
The hash property of the Location interface returns a string containing a '#' followed by the fragment identifier of the URL — the ID on the page that the URL is trying to target. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string, "" .
Window location. The replace() method replaces the current document with a new one.
To remove the hash URL, you can use the replaceState method on the history API to remove the hash location. Example: HTML.
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> ?
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(); });
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