How To Handle JavaScript Links

Once in a while, you need to create a link that does not actually link to anything. When that link is clicked, a javascript triggered action occurs such as a modal popping up or a cool menu animation occurs. So how do you construct that link? I used to take the simple approach and link it to a ‘#’, like this:

<a href='#'>natashatherobot.com</a>

But then I learned that a better way to handle is by linking to “javascript:void(0)” instead, like this:

<a href='javascript:void(0)'>natashatherobot.com</a>

There are several reasons the “javascript:void(0)” approach is better:

  • It prevents the page from scrolling to the top in certain browsers
  • It does not push another page onto the user’s browser history stack when they click on the link (so when they click the back button, it works as the user expects).
  • The above reasons are ones that someone explained to me. Here are some more reasons to read about on StackOverflow.

Do you know of other reasons to use “javascript:void(0)”. If so, let me know in the comments!

Enjoy the article? Join over 14,500+ Swift developers and enthusiasts who get my weekly updates.