views:

1088

answers:

3

add a hash to url without scrolling page? with javascript

  1. i open page
  2. i scroll down
  3. i click link that adds a hash (maybe with a value #test) (example: http://www.example.com/#test)
  4. the page MUST not scroll back to the top.

how can this be done?

note: just checking if it's possible to disable the movement even if there is some tag with id="test" so far the return false; works fine (to support people without javascript), and also to avoid the presence of the id's in the html, but it is not a problem with things like numbers, like 1, 2, 3 (they are not allowed as id's anyway)

all the answers are great, nothing new or groundbreaking, and no solutions on how to break the default functionality, but it will do. :) thank you for taking the time to answer.

+2  A: 

Any hash that isn't present on the page should give you this behaviour. For example, this link points to a non-existant hash on this page. (Link tested with Chrome 2.0 and IE 6 (the only browsers I have available to me at the moment).)

So if your URL is causing you to go to the top of the page, make sure you have nothing on the page whose id or name is that address.

Welbog
after so much time thinking, i realized that your absolutely right.
YuriKolovsky
A: 

Every browser will interpret the hash value as "go to that DOM ID". You could try two things I can think of:

  1. Make the action that adds the hash to return false, thus disabling the need of the browser to look it up

  2. Add a DOM tag with the ID of the hash you are adding right where the click is, to stop the browser to move. But probably this isn't what you want, since you are adding the hash for something.

Yaraher
A: 

Either of the examples below should do what you want:

<br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br>
<br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br>
<br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br>
<a href="pleaseEnableJS.html"
    onclick="window.location.hash = '#test1';return false;">Test 1</a>
<a href="#test2">Test 2</a>
<br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br>
<br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br>
<br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br>

If there is any element with id="test1" or id="test2" or <a name="test1"></a> or <a name="test2"></a> on your page, it will scroll to that element, otherwise it should work as you requested.

If you have code that is not working as expected, please edit your question and include a small example of the HTML and JavaScript that isn't working as expected.

Grant Wagner