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

57 views Asked by At

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.

2

There are 2 answers

4
idrumgood On BEST ANSWER

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.

0
Brad On

They always do this.

Note that the click action of your links can be overridden in JavaScript, which is why you may have seen different behavior before.