14

There is a javascript-based interface - so I need not to support work without javascript.

I have an

<a>Something</a>

elements with JS code, which binds on click event - so, I don't want page reload after user's click.

Which way is better?

1. <a href="javascript:void(0)">Something</a>
2. <a href="#" onclick="return false;">Something</a>

What advantages and disadvantages of each method?

Sir Hally
  • 2,318
  • 3
  • 31
  • 48
  • See also: http://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0 http://stackoverflow.com/questions/3451560/ideal-value-for-a-href-when-used-for-a-js-event – Christian C. Salvadó Aug 12 '10 at 08:03
  • 1
    duplicate ? see: http://stackoverflow.com/questions/245868/what-is-the-difference-between-the-different-methods-of-putting-javascript-in-an – Kai Sternad Aug 12 '10 at 08:05

2 Answers2

11

Both are poor choices. Presentation shouldn't mix with content. That means no javascript: URIs, and definitely no onclick attributes.

The way to do it:

<a id="myLink">Something</a>
<script>
    function myFunction(...) { ... }
    document.getElementById('myLink').addEventListener('click', myFunction, false);
</script>
Delan Azabani
  • 79,602
  • 28
  • 170
  • 210
  • In general, it is a second way - event listener. I have written onclick="..." for simplicity. I use JQuery - so $("#elementId").bind("click", function(){return false;}); Thank you. – Sir Hally Aug 12 '10 at 08:08
  • 1
    You're right that both are poor choices, but this is even worse: it doesn't work in IE. And how does this putting a ` – Tim Down Aug 12 '10 at 21:23
  • 3
    Sigh. I'm not getting deeply into the IE-is-bad-so-I'm-not-going-to-support-it issue again. I'll limit myself to pointing out that it's the user's choice which browser they use, not yours, and most users neither know nor care which browser they use. Some simply cannot switch. This case isn't even controversial: `addEventListener` doesn't even work in the current version of IE (8), meaning your code doesn't work in something like 50% of people's browsers. Do you really want to exclude 50% of people from using your website? – Tim Down Aug 13 '10 at 15:34
  • OK, that's your choice. However, it's fair to assume that the person asking the original question will be concerned about IE. – Tim Down Aug 14 '10 at 16:30
  • Another downside: this will cause the link not to be styled like other links, e.g. by default it wouldn't be underlined, because the `href` attribute is missing. – Matt Browne Jul 21 '15 at 03:59
  • Are AJAX interactions not a valid case for an anchor that doesn't go anywhere? – Scott Mar 29 '17 at 07:13