0

I have the following code:

 <a href="javascript: doSomeFunction();">Click here</a>

in Chrome it works well, but in other browsers, like Opera, Firefox, etc., it does nothing and an almost blank page opens, with the message "Object object" or something similar.

If I change the href call above by

<a href="#" onClick="doSomeFunction();">Click here</a>

it works well in all browsers, but the page moves to the top (scrollbar).

The third solution:

 <a href="javascript:void(0);" onClick="doSomeFunction();">Click here</a>

works perfectly for all browsers.

Still, in the wild I have found this recommendation:

<a href="javascript: doSomeFunction(); void(0);">Click here</a>

which is similar to the above one, but without the need of the onClick event.

Why is the best approach and why?

Cesar
  • 514
  • 1
  • 5
  • 16
  • 2
    Putting `javascript:` in href is not recommanded. Use `return false;` in the onClick to cancel navigation instead. – Kulvar Jun 03 '16 at 09:29

1 Answers1

3

The general consensus is that using href="#" is better than "javascript:void(0);" as "javascript:" doesn't degrade gracefully, so they should be avoided when possible.

The best solution would be your second solution:
<a href="#" onClick="doSomeFunction();">Click here</a>

To fix the issue with it scrolling to the top on click, simply change it to:
<a href="#" onClick="doSomeFunction(event);">Click here</a> (added event argument) and do event.preventDefault(); in your function.

So the code would look like this:

<a href="#" onClick="doSomeFunction(event);">Click here</a>

<script>
function doSomeFunction(event){
    // Do stuff

    event.preventDefault();
}
</script>
Lukas Gjetting
  • 175
  • 1
  • 10
  • 1
    As of HTML5, you can simply omit the `href="#"` - it's not graceful degradation anyway to scroll to the top. You should have a real link/anchor, or just none at all. – Bergi Jun 03 '16 at 09:43