Search code examples
javascriptonclickhrefvoid

Best way of calling a JavaScript function through an href attribute


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?


Solution

  • 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>