"href" attribute for links in JavaScript: "#" or "javascript:void(0)"?

Question:

Popularly, there are two methods of creating links that perform a function in JavaScript, they are:

<a href="#" onclick="myFunction();">Executar JavaScript</a>

Where

<a href="javascript:void(0)" onclick="myFunction();">Executar JavaScript</a>

Considering functionality, page loading, etc… Which is the most recommended?

Answer:

None.

Problems

  • Using any of these examples promotes "obstructive JavaScript" which makes the code difficult to maintain and not at all scalable.
  • Using javascript:void(0) does not allow users to open this link in a new tab, which can be frustrating.
  • Using javascript:void(0) violates the Content Security Policy (CSP) on secure pages (HTTPS).
  • Using # returns the user to the top of the page and requires a return false; so that it works correctly.

Conclusion

In my opinion, the tag button is most recommended that tag a , it can even take on the appearance of a link with CSS:

.link {
  background-color: transparent;
  border: 0;
  color: #00f;
  cursor: pointer;
  display: inline-block;
  padding: 0;
  position: relative;
  text-decoration: underline;
}

If using the button tag is not an option, the best way to write your code in these cases is to remove the href attribute, you are not obligated to use it at all. Any good CSS reset such as Normalize takes care of defaulting the cursor style so that usability can be maintained. Also, in order for you to have scalable and maintainable code, your logic needs to "remain" in JavaScript itself.

Example:

Your HTML:

<a class="action">Ação</a>

Your JavaScript:

var actionButton = document.querySelector('.action');
actionButton.addEventListener('click', myFunction);

/* Usando jQuery */
$('.action').on('click', myFunction);

Comments

  • Removing the href attribute from a causes an accessibility problem, as the element is no longer accessible by navigating through the tab key. You can define a tabindex or replace with a button , which can easily take on the appearance of a link.
  • Removing the href attribute from a causes hover related issues in Internet Explorer versions 6 and 7. If necessary, this can be easily solved with JavaScript.
  • If you want your link to continue working if JavaScript is disabled, use the href element and insert event.preventDefault() at the end of the JavaScript code action. This is a great example of graceful degradation .
  • In extreme cases, where JavaScript code control is limited, the best option is javascript:void(0) as it will cause the least problems.

Bonus

There is another method, which is to use a non-existent anchor by default, as in the example below:

<a href="#void" onclick="myFunction();">Executar JavaScript</a>

This method is very similar to the examples presented, although this way the page will not go up. Even so, the code remains obstructive.

Scroll to Top