ipodppod
ipodppod

Reputation: 112

How do I stop the browser from scrolling to the top when an "#section" link is clicked

I have the following link:

<a href="#section">Section</a>

Now I really want this link to be working so the url will be changed to

mypage.html#section

But than on the other hand, if I just keep the code as it is, the browser would scroll the page back to the top automatically, and I don't want that to happen.

Obviously return false; will not suffice because it will not change the url.

Any ideas?

(Thanks)

Upvotes: 1

Views: 328

Answers (1)

Dustin Laine
Dustin Laine

Reputation: 38503

You are attempting to click an anchor that ties to a hash. Which is going to attempt to jump to the the appropriate element with that name. If it does not find that name it will just end up at the top. This is normal behavior.

It seems like you want to change that, from which I recommend not using and anchor and adding the #section hash via JavaScript:

<a href="#" onclick="document.location.hash = '#section'; return false;">Section</a>

That should give you your desired result.

Upvotes: 3

Related Questions