0

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.

Community
  • 1
  • 1
Eli Rose
  • 6,788
  • 8
  • 35
  • 55

2 Answers2

2

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.

idrumgood
  • 4,904
  • 19
  • 29
  • What is `e` in this context -- an event object? How would I use this function inside an `href`? – Eli Rose Jun 08 '15 at 21:04
  • @EliRose You wouldn't. In the `href` case where you have the `javascript:` protocol handler, the context is disconnected from the event. At a minimum, you would use `onclick` and then you could use any JS you wanted. – Brad Jun 08 '15 at 23:41
  • You're right, of course -- I said `href`, but was thinking `onlick`. How do I access the event object from within `onlick`? – Eli Rose Jun 08 '15 at 23:43
  • If the function you call is expecting the `event` argument (as the example above is), it will just be there. You don't need to explicitly pass it to the `onclick` – idrumgood Jun 09 '15 at 14:45
1

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.

Brad
  • 159,648
  • 54
  • 349
  • 530