Eli Rose
Eli Rose

Reputation: 6998

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.

Upvotes: 0

Views: 44

Answers (2)

idrumgood
idrumgood

Reputation: 4924

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.

Upvotes: 2

Brad
Brad

Reputation: 163262

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.

Upvotes: 1

Related Questions