javascript anchor avoid scroll to top on click

前端 未结 5 1612
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 14:47

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

javascript :

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

html :

相关标签:
5条回答
  • 2020-12-08 15:11

    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.

    0 讨论(0)
  • 2020-12-08 15:14

    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 讨论(0)
  • 2020-12-08 15:20

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

    <a href="#" onclick="somefunction(); return false;">anchor</a>
    
    0 讨论(0)
  • 2020-12-08 15:22

    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.

    0 讨论(0)
  • 2020-12-08 15:27

    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>
    
    0 讨论(0)
提交回复
热议问题