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.
Javascript Avoid Scroll To Top On Link Click
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.