Accessibility for Web Components

Accessibility plays a vital role in web development. Our users can be limited to a keyboard, they might be using a screen reader, or could be color-blind. Making sure that our users are comfortable in all scenarios is the key to making a good site. Similarly, creating a good Web Component also includes making a Web Component accessible. 

When you are creating a Web Component, you need to make sure that your Web Components are accessible at least up to a certain extent. For example, an image should always have alt text. A link should always have alt text. Input fields should have proper aria-labels. There should be sufficient color contrasts. Tab orders should be in the correct order, and so on

Now that we know what can be done to make a component accessible, let's take a look at a small example. Let's say the requirement is to create a <header-image> component that shows a full-width image. In order to make sure that this component is accessible, the image used should have alt text. 

Let's take a look at our getTemplate() function for this component:

getTemplate() {
return `
<img src="${this.getAttribute('src')}"
alt="${this.getAttribute('alt')}"/>
${this.handleErrors()}
<style>
img {
width: 400px;;
}
</style>
`;
}

Here, we are adding an alt attribute to the image tag, and we are grabbing this alt text from the Web Component itself:

<header-image alt="Blue Clouds"
src="clouds-sky-header.jpg">
</header-image>

We also have an error handler function called handleErrors(), which makes sure to tell the user that the component is missing alt text:

handleErrors() {
if(!this.getAttribute('alt')) {
return `
<div class="error">Missing Alt Text</div>
<style>
.error {
color: red;
}
</style>
`;
}

return ``;
}

This will show a Missing Alt Text error message in red, when the component is missing the alt text. We can solve other accessibility issues in the same way.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.42.196