Which is the proper "href" value in JavaScript for links: "#" or "javascript:void(0)"?


In this article we are going to talk about the differences of using "#" or "javascript:void(0)" in the href attribute. Usually you are using this particular values in href to trigger the onclick and avoid the user to change the current url.

WARNING it's not recommended to use "#" or "javascript:void(0)", please refer to the documentation of your javascript framework to write the proper code.

Here are two examples, one with "#" or and another using "javascript:void(0)":

<a href="#" onclick="clickOnLink();">Link</a>
<a href="javascript:void(0)" onclick="clickOnLink();">Link</a>

The code of the clickOnLink is not relevant, but it contains the code that you want to execute when the user clicks the "Link".

Answer use "javascript:void(0)"

If you are trying to use "#" or "javascript:void(0)" in href on modern javascript you are probably doing something wrong. Make sure you know what you are doing. Having said the warning about using those values in href, if you need to choose between those two we recommend to use "javascript:void(0)".

If you are going to use "#" in href you have to consider several scenarios:

  • onclick always contains return false; at the end.
  • called function must not throw an error.
  • if you attach a function dynamically to the onclick property make sure observations below are satisfied.

While using the "#" and not adding the return false; at the end of the function, it will take the user back to the top of the page. Also if you include the return false; and any function called returns an error the return false; will not be executed! When using javascript:void(0) you don't need to assert for the conditions mentioned below.

Remeber that using "#" or "javascript:void(0)" promotes the practice of obtrusive JavaScript and there are better ways of solving the required task.

The jQuery way

If you are using jQuerys don't use the "#" or "javascript:void(0)".

As an example if you are using jquery, the proper code to solve the problem is:

// Cancel click event
    alert('The message!');

While on the HTML:

<a class="message-action">Show the message</a>

Modern Javascript frameworks

If you are using a javascript framework like Angular, ExtJS, etc make sure you read the documentation of those framework to use the proper code. We suggested a solution using jQuery, but that solution is not valid if you are using Angular (since mixing jQuery events with angular is a bad idea). When using angular check ngClick docs.