Simple Tip : Disable Scrolling To Top On Link Click
Whenever we have a hyperlink which does not take you to the different page and its value is “#” then we generally get into this problem that – on clicking on hyperlink, page url is appended with # and focus is moved to top of the page.
Javascript Solution:
To avoid page focus moving to top and page getting scrolled to top, we can return 0 when a anchor or hyperlink is clicked on a webpage.
So just change the value from “#” to “javascript:void(0)”
<a href=”javascript:void(0)”>Sample Hyperlink</a>
Now with above trick, click will happen and user will be at same place instead of scrolling to top.
You might be thinking whats the use of this ?
We can write onclick event and perform some operation or we can write javascript or jquery handler which will perform some operation.
But in any case our focus will be at the same position, instead of scrolling and getting lost.
JQuery Solution :
If you are using JQuery and want to achieve same functionality then in JQuery we can call “event.preventDefault()” method to block default behavior.
So whenever we write click event of any anchor tag / hyperlink then at the end of the function, if we write event.preventDefault() then it will do the work.
If you know any other solution then let me know, I would love to add it here.
Just return false on your onclick..
Please don’t link to javascript:void(0). It can break the page’s navigation in strange ways, especially when you try to open the link in a new tab or new window. Using a real valid url and calling the preventDefault method on the event object is the best solution by far. If you are unable to do this for some reason, reconsider why you are using the element, perhaps a or or something else would be better for your scenario.