开发者

javascript anchor avoid scroll to top on click

开发者 https://www.devze.com 2022-12-17 20:00 出处:网络
I created a function in javascript that i add to an anchor as such javascript : somefunction = function () {alert(\'foo\')}

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 开发者_如何学Goit?

thank you


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.


Return false from your onclick handler, e.g.:

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


You need to make somefunction() return false, or you need to explicitly add return false to your onclick handler. For example:

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

This will have the browser ignore the href portion of the link when someone clicks on it.


I know that the question is asked for JavaScript, but if anyone would like to do it in jQuery then it is pretty simple.

You can give your a tag an id and reference it in jQuery to do a certain action.

All you need to do, - to avoid the scroll to top is to disable the default action of the a tag.

Code:

$( "#a-tag-id" ).click(function(e) {
        e.preventDefault();
        alert( "Hello World" );
    });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号