Tip: Avoid "javascript:void(0)" for empty links

JavaScript, Browser, Accessibility · Jun 12, 2021

There are various ways to create an empty link, but some options are more appropriate than others. One of the most common debates about it is if one should use href="", href="#" or href="javascript:void(0)".

Generally, you want to avoid href="javascript:void(0)", as it will cause the browser to parse the value of the link URL, which is both costly and unnecessary. It also introduces a potential XSS security vulnerability, as javascript: URLs violate Content Security Policy (CSP).

With that out of the way, it's clear that href="" or href="#" should be preferred in most cases. One key difference between the two is that href="#" points to the top of the page whereas href="" points to the current page. This can have unwanted side-effects, such as scrolling to the top of the page or issues with link styling respectively. To prevent either one of them from acting as links, you can use Event.preventDefault() and handle them appropriately using JavaScript.

Finally, when creating an empty link, one should always consider more semantically appropriate alternatives, such as a <button>, <div> or <span> tag. After all, a link should always behave like a link and hijacking it with JavaScript or any other means is bound to run into some accessibility problems sooner or later.

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • Tips & Tricks

    A collection of quick tips and tricks to level up your coding skills one step at a time.

    Collection · 53 snippets

  • Add multiple listeners

    Adds multiple event listeners with the same handler to an element.

    JavaScript, Browser · Oct 22, 2020

  • Create HTML element

    Creates an element from a string (without appending it to the document). If the given string contains multiple elements, only the first one will be returned.

    JavaScript, Browser · Oct 19, 2020

  • URL parameters as object

    Creates an object containing the parameters of the current URL.

    JavaScript, Browser · Oct 22, 2020