How to make a Button accessible?

How to make a Button accessible?

How to make a Button accessible?

Please take look at my previous blog about accessibility. I have chosen first to cover making button accessible because as the button is the main call to action for a website and we use more no of buttons in the website.

What makes the button accessible.

To make a button accessible it should have the following four things while we navigating the website through the screenreader.

  • First It should have a button name.
  • It should announce the role as a button.
  • It should have tab access while using the keyboard.
  • It should also be operable either using Enter key or Spacebar

Common ways to make an accessible button.

I have come across these four ways to make a button.

By using button tag.

The easiest way to make a button accessible is to use a semantic button tag.

<button>Help</button>

This will have all the four necessary things by default.

The link tag will have 3 necessary things such as name, tab access, and operable through Enter key by default. We only need to add a role as the button to make it a button. It can be added by adding role='button' in the link tag.

<a href='https://www.google.com/' target='_blank' role='button' class='btn'>Google</a>

By using the image/icon.

The next common way of making buttons is using images/icons. To make the image/icon an accessible button we should enclose it by using a button tag and providing the name using an aria-label attribute. It will now have all the necessary four conditions.

<button class='btn' aria-label='Help' onclick='showalert()'><i class="fas fa-question-circle" ></i></button>

By using the div tag.

The next common way of making buttons is using a div tag.

<div id='divButton' onclick='showalert()' tabindex='0' class='btn' role='button' >Help</div>

To make div a button we need to add the following things.

  • First, we have to give role='button' to make it announce as a button by the screenreader.
  • Next, we have to add tabindex='0' to give tab access while using the keyboard.
  • Tabindex only gives the tab access to make it operable using Enter/Spacebar we need to add the following javascript code.
var divButton=document.querySelector('#divButton');

divButton.addEventListener("keydown", e => {
if (e.key === " " || e.key === "Enter" || e.key === "Spacebar"){
   divButton.click();
}});

Now it has all four necessary conditions.

These are the ways how we can make the button accessible.

Take look at the examples on codepen.

Summary

To make a button accessible it should have the following four things...

  • First It should have a button name.
  • It should announce the role as a button.
  • It should have tab access while using the keyboard.
  • It should also be operable either using Enter key or Spacebar