Prevent page from scrolling to top after link click

By | 15 April, 2014

Imagine you have a bunch of links, maybe images, or anything else, that dont actually have a url to jump to but instead trigger some awesome javascript that do amazing things somewhere else, or just highlight the icons/images as selector of whatever. If you use links like

<a href="#" onclick="doStuff(1)">link1</a>
<a href="#" onclick="doStuff(2)">link2</a>
<a href="#" onclick="doStuff(3)">link3</a>
...

When you click on these links, they do trigger all your amazing stuff, but they also make your page scroll to the top if they are below the height of your browser window.

On for the code and simple solution, well, two of them, after the jump:

You can change the tags like this (note the exclamation mark after the #):

<a href="#!" onclick="doStuff(1)">link1</a>

In this case you make the link fail to linking to a part of the document, therefore keeping the page still – the issue is not exactly the exclamation mark (read the link at the end of the article to learn more).

Or like this:

<a href="#" onclick="doStuff(1);return false;">link1</a>

In this case you prevent the link from going full cycle.

If you want to get technical about it, go read here:

Stack exchange topic about this