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
Just use "#/" instead of "#" and the page won't jump. This need to be the best answer.
window. scroll(0, 0) will work just fine in all browsers.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With