Search code examples
htmlwebhref

Under what conditions does href="#" cause scrolling to the top of the page?


I was using <a href="#" onclick="f();">click here</a> type tags to trigger actions on my website. I swear they didn't used to do this, but now when I click one of them, the browser scrolls to the top of the page.

Having found this answer, I am now using href="javascript:;" which works great. But I can't be the only one with this problem (unless I am). I'd really love to know when href="#" behaves this way and when it doesn't.


Solution

  • Always, unless your javascript handler prevents it.

    function f(e) {
        e.preventDefault();
    }
    

    Now if your click calls f(e) you will not scroll to the top.