Never Use Onclick for Navigation

May 8, 2019
You know what really grinds my gears? Bad websites.

One thing I see again and again, is websites using javascript onclick events for navigation instead of <a href> links.

There's (hopefully) only a very small group of developers actually doing this, but I still see this too much, to write a post about it.

What's the problem, you might ask. Well, have you tried right-clicking on such an element, and clicking "Open link in new tab"? Guess what, it doesn't work. The browser doesn't know it's a link.

Neither does:

The solution is easy: Always use <a href> elements for navigation links.

So When Can I Use Onclick Instead of <a>?

If the link (or button) URL should NOT be opened in a new tab or copied/shared.

If you're making a webapp or a confirm/alert for something the user is doing correct (or wrong), like submitting a form, it's perfectly fine to use onclick events, since opening in a new tab, or copying the link wouldn't make sense.

Single Page Application

If you're developing a SPA, you probably want both onclick and <a href="">, so the user can copy and share the URL, and still be able to get the scroll/fade effects when clicking.

SEO & Accessibility

Don't do this just to please me or your users, this also makes it easier for crawlers and screen-readers to find your links.

Follow RSS/Atom Feed
See more posts