Add a fragment to the URL without causing a redirect?
117,921
Solution 1
window.location.hash = 'something';
That is just plain JavaScript.
Your comment...
Hi, what I really need is to add only the hash... something like this:
window.location.hash = '#';
but in this way nothing is added.
Try this...
window.location = '#';
Also, don't forget about the window.location.replace()
method.
Solution 2
For straight HTML, with no JavaScript required:
<a href="#something">Add '#something' to URL</a>
Or, to take your question more literally, to just add '#' to the URL:
<a href="#">Add '#' to URL</a>
Solution 3
window.location.hash = 'whatever';
Author by
Dee
Updated on October 03, 2020Comments
-
Dee almost 4 years
Is there is a way how to add hash # to my URL without redirect?
-
user3167101 over 13 yearsThe
#
prefix is not required. -
Daniel Lo Nigro over 13 years@alex: Ah, I wasn't too sure whether it was required or not. window.location.hash returns the hash with a # prefix, so I assumed it was. Thanks for the clarification. :)
-
user3167101 over 13 yearsNo worries - and it makes you wonder why it always returns it.
-
Dee over 13 yearsHI, what i really need is to add only hash... something like this: window.location.hash = '#'; but in this way nothing is added..
-
Juan almost 9 yearsnot correct, as you need to click the link to change the hash.. so you are missing the js part where you trigger the "click"..
-
Jess Telford almost 9 years@Juan Why do we need to "trigger" a click? The original question just asked how we can add the
#
to the URL. Actually clicking a link as I suggested will fulfil that. No JS necessary. -
Juan almost 9 yearsYour answer describes how to create a link that, WHEN clicked, adds a fragment to the url. The question asks how to add a fragment. So your answer is missing the action, that is, the "click"
-
Jess Telford over 8 yearsFair enough, I can see the question being interpreted that way. Hopefully someone will still find this option useful for their use case.