15

I occasionally see an HTML <a> element whose href attribute is a URI that has just javascript for the scheme, and an empty statement ; for the path.

  • What is the purpose of this?

  • Is it the same as href="javascript:void(0);"?

  • Is it the same as having no href attribute at all?

  • Is it the same as having no <a> element at all?

Update

The precise content that I am seeing is <a href="javascript:;" style="cursor: default;"></a>. So is this just a way of controlling the cursor graphic?

Borodin
  • 126,100
  • 9
  • 70
  • 144

1 Answers1

6

You can understand by below some steps:

<a onclick="foo()">Next Image</a>
<a href="#" onclick="foo()">Next Image</a>
<a href="javascript:foo()">Next Image</a>
<a href="javascript:void(0)" onclick="foo()">Next Image</a>
<a href="#" onclick="foo(); return false;">Next Image</a>

method 1 usually won't change the mouse cursor to a "hand cursor", so maybe it is not as desirable in some cases.

method 2 seems to cause the page to shift to a new location sometimes on IE 6 and IE 7. (to top of page?)

method 3 ... should work... but is it an old school way and should be avoided for modern browsers?

method 4 should work well.void-the-void/ the author seems to suggest it may break sometimes and try never to use href="javascript:[anything]"

method 5 may work the best? according to the article above, that may be the best way as it doesn't use href="javascript:[something]" and the return false part will cause the href="#" not to be evaluted, so that's the best way? thanks very much!

Manoj Saini
  • 339
  • 2
  • 8
  • 1
    Thank you. Where does `` fit into this scheme? – Borodin Apr 23 '14 at 09:59
  • href="" will link to the same page as the one you are currently on, effectively refreshing the page. href="#" will not refresh the page, but using the # will make the screen move to the top of the page (it is the browser effectively looking for an anchor with no name, ). javascript:void(0) will prevent anything happening on the link at all. – Manoj Saini Apr 23 '14 at 10:04
  • Thank you again, but you haven't addressed my question about `href="javascript:;"` – Borodin Apr 23 '14 at 10:06
  • When we create a link for solve our purpose to run JavaScript code, there are 2 ways to write the code. Which is better, in terms of functionality, page load speed, validation purposes, etc? Run JavaScript Code Run JavaScript Code – Manoj Saini Apr 23 '14 at 10:11
  • I understand, but you still haven't mentioned `href="javascript:;"`. Where does it fit into this scheme? – Borodin Apr 23 '14 at 10:14
  • Here is an earlier answer on SO regarding the semicolon usage (that's not valid JavaScript, and can cause an error on some browsers) http://stackoverflow.com/questions/10880996/javascript-for-href-attribute-in-html-anchor-tag – DenizEng Feb 17 '16 at 11:53