Anchor, Button or...

Anchor, Button or...

Be sure to pick the right tool for the right task

Question: you want to offer a user some form of interaction. What will you use? A <button>, an <anchor> or another HTML element?

Anchors

Anchor should be used for navigation (inside the same page or towards another) and to reference external files and resources.

<a href="path/to/resource/" title="I act as a tooltip" target="_self">Visible text or image tag</a>

title: you can use it to offer additional info, that appears when the cursor hovers the link, like a tooltip.

target: if its value is "_blank", lets the resource open in a new browser page.

Keyboard interaction: it activates with Enter key

Buttons

Buttons should be used to trigger actions that do not require navigation.

<button type="button" title="I act as a tooltip">Button text</button>

type: always specify the type. "button" makes it only clickable (you have to bind actions via JS), "submit" triggers a form submit, "reset" clears all the data inserted in a form.

disabled: makes the button unclickable, but also unfocusable. Screen readers don't announce elements with "disabled" attribute, so this element could be potentially inaccessible. It's not a useless feature, but keep that in mind when using it.

aria-disabled\="true": semantically, the button is as well disabled, but it is focusable and it is announced from SR. You can also use the "title" attribute to show a tooltip when hovering it, potentially explaining why the button is disabled. Unfortunately, you have to manage its behaviour manually with JS and CSS ('cause you should style it differently).

Keyboard interaction: it activates with Enter or Spacebar key

Making aria-disabled buttons unclickable

The procedure is quite straightforward: using event.preventDefault() should be enough for the majority of cases. If you don't know how, here's a quick snippet:

<script>
document.getElementById('myButtonId').addEventListener('click', (event) => {
    if(event.target.getAttribute('aria-hidden') === "true") {event.preventDefault();}
});
</script>

And here is a quick demo in codepen:

...or other Html Elements

With these two options available, do you really need other elements to act as anchors or buttons? I bet you don't need these but...

if you really, inevitably, undoubtfully, inexorably need... don't limit your code to appear like anchors or buttons, explain the system that these elements should be considered as anchors/buttons with the "role" attribute (in case, add also a tabindex="0" to ensure the element is focusable):

<div role="link" tabindex="0">This will be interpreted as a link</div>
<div role="button" tabindex="0">And this as a button</div>