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';
Share:
117,921
Dee
Author by

Dee

Updated on October 03, 2020

Comments

  • Dee
    Dee almost 4 years

    Is there is a way how to add hash # to my URL without redirect?

  • user3167101
    user3167101 over 13 years
    The # prefix is not required.
  • Daniel Lo Nigro
    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
    user3167101 over 13 years
    No worries - and it makes you wonder why it always returns it.
  • Dee
    Dee over 13 years
    HI, what i really need is to add only hash... something like this: window.location.hash = '#'; but in this way nothing is added..
  • Juan
    Juan almost 9 years
    not 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
    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
    Juan almost 9 years
    Your 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
    Jess Telford over 8 years
    Fair enough, I can see the question being interpreted that way. Hopefully someone will still find this option useful for their use case.