Some elements have semantic meaning but no special functionality. Examples are:
Other's provide a lot of built-in functionality such as:
Form fields can be confusing for screen reader users. There are many ways to label form fields so the label is read out loud whenever the field has focus.
A common pattern is using div's or paragraph tags to label form fields.
<form>
<p>First Name</p>
<input type="text" />
<p>Last Name</p>
<input type="text" />
<p>Password</p>
<input type="password" />
<input type="submit" value="Submit" />
</form>
A better option is to use the HTML label tag which will allow screen readers to recite the label when the field is focused.
<form>
<label for="first">First Name</label>
<input id="first" type="text" />
<label for="last">Last Name</label>
<input id="last" type="text" />
<label for="password">Password</label>
<input id="password" type="password" />
<input type="submit" value="Submit" />
</form>
Another cool trick you can do is wrap your inputs with the label tag. This is called implicit labelling.
<form>
<label>
First Name
<input id="first" type="text" />
</label>
<label>
Last Name
<input id="last" type="text" />
</label>
<label>
Password
<input id="password" type="password" />
</label>
<input type="submit" value="Submit" />
</form>
The label tag can only works with "labelable" elements. Those include:
If you ever need to label an element not on that list, use aria-label instead.
<div aria-label="Interactive div">Hello</div>
Sometimes you'll want to communicate with a screen reader directly! One cool example is announcing to screen reader users that you offer accessibility features! In that case you can make some HTML and wrap it in a visually hidden class.
.visuallyhidden {
position: absolute;
left: 0;
top: -500px;
width: 1px;
height: 1px;
overflow: hidden;
}
Let's take a regular button like the one below:
This is generated by the following code:
<button onclick="alert('hello')">Click me!</button>
This looks like a simple piece of markup but there is a lot of functionality behind that button tag!
Let's start with a different element, say a div tag.
<div onclick="alert('hello')">Click me!</div>
This will let screen readers know the element can be clicked.
<div role="button" onclick="alert('hello')">Click me!</div>
This will allow keyboard only users to tab to it.
<div tabindex="0" role="button" onclick="alert('hello')">Click me!</div>
<div tabindex="0" role="button" onclick="alert('hello')" onkeyup="alert('hello')">Click me!</div>
<div aria-label="Alert the word hello" tabindex="0" role="button" onclick="alert('hello')" onkeyup="alert('hello')">Click me!</div>
For the next exercise, click here