Handling Focus for Components

By in
334
Handling Focus for Components

Program your components to recognize which element is the focus and which can accept input if you want them to be accessible to persons with impairments.

The tab key on the keyboard can be used to navigate web browsers in their entirety. Users who utilize keyboard navigation need a visual cue to know which element is in focus for accessibility reasons. Screen readers are also used by those with low eyesight to navigate websites. The focus element is read aloud by screen readers along with the other components on the page. As a developer, you must make sure that the browser shifts the emphasis to the following logical element whenever a user tabs across a page.

Interactive components like a>, button>, input>, and textarea> immediately receive focus as a user tabs through a website. Tabindex=”0″ can be used to give keyboard emphasis to elements that are not naturally capable of receiving it, such div and span tags.

The only supported tabindex values are 0 and -1. When the element’s tabindex attribute is set to 0, ordinary sequential keyboard navigation is used. If you provide it tabindex=”-1,” the element is taken out of consecutive keyboard navigation.

Focus shifts away from the component container and toward the elements contained within custom components.

Now let’s examine some code.

In this illustration, the user’s focus switches from a button element in the parent to an input element in the child when they tab, skipping the child element entirely.

 

<!– parent.html –>

<template>

<button>Button</button>

<c-child></c-child>

</template>

 

<!– child.html –>

<template>

<span>Tabbing to the custom element moves focus to the input, skipping the component itself.</span>

<br /><input type=”text”>

</template>

 

Attribute Focus Element
Image Source: Developer.Salesforce

Now to fix it, we can modify the code by adding a tab index to the child component as shown above.

 

<!– parent.html –>

<template>

<button>Button</button>

<c-child tabindex=”0″></c-child>

</template>

 

Conclusion

In this way, we use the tabindex attribute to give a custom component focus. To include the child component itself in the navigation sequence, we set the tabindex of the child component in the parent template to 0.

 

To learn more about accessibility attributes, check out my related post below!

 

Additional Resources

Cover Photo by Paul Skorupskas on Unsplash

Leave a reply

Your email address will not be published. Required fields are marked *