4

I have a click in the middle of a website with code like <a href=“#“ onclick=“…

The function works well, but the a href=“#“ let’s the page always jump to the top when I click on the link. Is there any way around it?

Thanks

thedayturns
  • 9,723
  • 5
  • 33
  • 41
Denise
  • 1,453
  • 4
  • 14
  • 14

4 Answers4

17

Just add ; return false; to the end of your onclick, for example:

<a href="#" onclick="alert('hello'); return false;">

Edit: Hemlock's answer is a good alternative, but yet another one is a combination of the two:

<a href="javascript:void(0)" onclick="alert('hello')">

The advantage of this is that you're explicitly saying that the <a> should do nothing with the href, and the onclick event handler is a separate attribute. If you later decide to attach the onclick handler using JavaScript rather than inlining it (recommended), it's simply a matter of removing the onclick attribute.

David Tang
  • 92,262
  • 30
  • 167
  • 149
  • `href="javascript:"` works for me too. Is it not the same as `javascript:void(0)` ? – Nikita Rybak Jan 18 '11 at 13:26
  • @Nikita good question, I haven't seen just "javascript:" but it appears to work. I don't have IE to test with at the moment though. – David Tang Jan 18 '11 at 13:38
  • Wouldn't href="javascript:" be like declaring this is javascript and the not running anything and when you add void(0) it runs the void function which does:"The void operator evaluates the given expression and then returns undefined". https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void – Michael J. Calkins Aug 07 '13 at 20:17
4

Alternate method

<a href="javascript: alert('hello'); void(0);"></a>

Put the javascript in the href and make sure the code ends in a call to void

Hemlock
  • 6,130
  • 1
  • 27
  • 37
2

add

return false;

at the end of the onclick statement

that is

<a href="#" onclick="alert('test'); return false;"> Click Here </a>
Umair Jabbar
  • 3,596
  • 5
  • 30
  • 42
0

if you want an element that does some javascript onclick, you should not use the a tag. The a tag is for navigation from one page to another. You should use span and then you don't have to provide a href attribute. The problem lies in the fact that you chose the wrong HTML element for your case.

<span onclick=""></span>
Bazzz
  • 26,427
  • 12
  • 52
  • 69
  • 2
    The reason to use a focus-able element for click is for keyboard navigation, required for accessible sites. A user can tab to an a element to focus, and press enter to 'click' it. – kennebec Jan 18 '11 at 13:32