Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript anchor avoid scroll to top on click

Tags:

javascript

I created a function in javascript that i add to an anchor as such

javascript :

somefunction = function () {alert('foo')} 

html :

<a href="#" onclick="return somefunction()">anchor</a> 

everytime i click on the anchor the function executes but the screen scrolls to the top

I know i could do this

<a href="javascript:void(0)" onclick="return somefunction()">anchor</a> 

but I have seen the first option implemented without this hick up of scrolling up

is there any trick to it?

thank you

like image 834
salmane Avatar asked Jan 18 '10 08:01

salmane


People also ask

How do I stop clicking links from jumping to top of page?

Just use "#/" instead of "#" and the page won't jump. This need to be the best answer.

How do you scroll to top when a button is clicked?

window. scroll(0, 0) will work just fine in all browsers.

How do I stop scrolling when scrolling a div element CSS?

CSS solution To stop the scroll at the end of an element, set on the element's CSS: overscroll-behavior: contain; This way, if the user reaches the end of the scroll of an element, it will stop there and not “scroll-chain” to the body or parent element.


2 Answers

The onclick causes the page to resubmit, therefore scrolling to the top.

You need the onclick event to return a false in order to avoid the postback.

This can be done by changing your function to return a false:

somefunction = function () {alert('foo'); return false;} 

Or to change the link and onClick event to do so:

<a href="javascript:void(0)" onclick="somefunction(); return false;">anchor</a> 
like image 161
Oded Avatar answered Sep 21 '22 23:09

Oded


The trick is that your onclick returns the value of somefunction, so that if you make sure somefunction always return false, then the event will return false as well, and cancel the default behavior of the anchor.

So this should solve your problem:

somefunction = function () { alert('foo'); return false; } 

But I should mention that when there is an error somewhere in somefunction, the rest of the javascript will not execute, and the browser will still follow the link to #. It is advisable, therefore, to use javascript:void(0) instead, as this will rid you of that problem.

like image 42
David Hedlund Avatar answered Sep 18 '22 23:09

David Hedlund