If It Navigates, Use an Anchor Tag
It is surprising how often developers use buttons for navigation. The problem with buttons is that they don't communicate what they do, at least not in a good way. But it's tempting to use them for navigation, like when you want to use a JavaScript function to navigate. An example would be the execution of history.back()
on a button press. It might look like the following:
<!-- HTML -->
<button type="button" id="back">Go Back</button>
// JavaScript
document.getElementById("back")?.addEventListener("click", () => {
history.back();
});
The problem here is that the button doesn't communicate that it navigates. That's why it is discouraged to use it for such a task. Use an anchor tag instead. Always. Here's how the previous example would look like using an anchor tag instead of a button:
<!-- HTML -->
<a href="/" aria-label="Navigate to the previous page" id="back">Go Back</a>
// JavaScript
document.getElementById("back")?.addEventListener("click", (evt) => {
evt.preventDefault();
history.back();
});
Yes, it's that simple. Calling preventDefault()
on an event caused by clicking an anchor tag prevents navigation. The element communicates to users what it does. There's no excuse to use buttons for navigation.