Home >Web Front-end >JS Tutorial >Writing JavaScript with Accessibility in Mind
This article will share some tips on how to improve the accessibility of JavaScript components and provide users with more and better ways to interact with websites or web applications.
This article was originally published on Medium
In my first article, Writing Accessible HTML, I explained why and how to start focusing on web accessibility and shared some tips on how to improve tagging to make a website more accessible. Some of these tips are very basic, but still valuable. It all comes down to two of the most important unwritten rules in front-end development: learn the basics and spend enough time planning and writing HTML. Clearly semantic markup will benefit you and your users.
Luckily, HTML is not the only language we make websites, but the more complex the language, the more likely it is to make mistakes, and JavaScript can become very complex. When we focus on whether the code works, it is easy to forget users who use input devices other than the mouse or touchpad, such as keyboard or screen reader users. In the second of this four article on web accessibility, I have collected some tips on what to consider when writing JavaScript and how to make JavaScript components more accessible.
Key Points
<button></button>
element when you need a button, is critical to accessibility. Misuse of HTML elements can cause problems for keyboard and screen reader users. JavaScript is not an enemy
Before reading my tips, I want to point out the important point – creating accessible websites does not mean you have to decide whether to use JavaScript or not. Accessibility is about getting content as many people as possible, which also includes users using old browsers and computers, slow internet connections, strict security restrictions (e.g., without JavaScript), and so on. The experience may not be ideal in situations like JavaScript may not work or load too long, but it is still good enough if the website is accessible and available.
If JavaScript is executable, it can even be used to improve accessibility. Sara Soueidan wrote about her experience creating tooltip components in Building a fully accessible help tooltip...harder than I thought. She explains why “every JavaScript-free solution comes with a very bad disadvantage that negatively affects the user experience” and why JavaScript is important for accessibility.
Marco Zehe in his article "JavaScript is not the enemy of accessibility! 》 writes more about JavaScript and accessibility. I highly recommend you read his article.
But that's all for the introductory conversation! Let's get started...
Good focus management is essential
It is very important to make sure our website can be navigated via the keyboard. Many users rely on the keyboard when browsing web pages. These include people with movement disorders, blind people, and people who are unable to use a mouse or touchpad for some reason.
Navigating the website through the keyboard means jumping from one focusable element to another focusable element in DOM order. This is usually achieved by using the Tab key or Shift Tab> . Focusable elements include links, buttons, and form elements. They can be selected using the Enter keys, and sometimes using the Spacebar. They have very useful default features by being focused and selectable in different ways. Therefore, it makes sense to use the correct semantic elements and write HTML in logical order.
Elements such as <div>, <code><span></span>
, or <div> cannot be focused by default. We often use these tags to create custom components powered by JavaScript, which can be problematic for keyboard users.
<p><strong>Make the non-focusable elements focusable</strong></p>
<p>You can make the non-focusable element focusable by adding <code>tabindex
attributes and integer values. If the value is set to 0, the element becomes focusable and accessible via the keyboard. If the value is negative, the element is programmatically focused (for example, using JavaScript) but is not accessible via the keyboard. You can also use values greater than 0, but this will change the natural Tab order and be considered an anti-pattern.
<code class="language-html"><h2 tabindex="0">一个可聚焦的标题</h2></code>
If you want to learn more about tabindex
, watch Rob Dodson's A11ycasts episode "Control Focus with Tabindex".
Focus elements using JavaScript
Even if the elements are focused, sometimes they are not in the correct DOM order. To illustrate this, I created a simple modal window component (demo and editable Pen) in HTML, CSS, and JS.
If you use the Tab key to jump to the button and press Enter, a modal window will pop up. If you press the Tab key again, the focus will jump to the next link that is visually displayed below the modal window. The expected behavior should be the next focused element within the modal window. But this is not the case, because the elements are focused in DOM order, and the modal window is at the bottom of the document. You can see its actual effect in this screen recording.
To solve this problem, you have to make the modal window focusable and then focus it using JavaScript.
<code class="language-html"><h2 tabindex="0">一个可聚焦的标题</h2></code>
You can see this in the updated examples (demo and editable Pen) by switching the Tab key to the button, press Enter and press the Tab key again. You will see that the modal window itself has now gained focus.
This is good, but there are still two problems here.
If you close the modal window by pressing Esc, the focus will be lost. Ideally, the focus should jump back to the button before you opened the modal window. To achieve this, you have to store the last focused element in a variable.
We can use document.activeElement
to get the element currently gaining focus.
<code class="language-javascript">function showModal() { var modal = document.getElementById('modal2'); modal.focus(); ... }</code>
Now that you have a reference to the button, you can focus it again when you close the modal window.
<code class="language-javascript">var lastFocusedElement; function showModal() { lastFocusedElement = document.activeElement; var modal = document.getElementById(modalID); modal.focus(); ... }</code>
I have updated the code in another Pen (demo and editable Pen). Accessibility is much better now, but there is still room for improvement.
It is recommended to keep the focus inside the modal window when opening the modal window. The modal window can still be popped up now. I won't go into details here, but for the sake of completeness, I created a fourth Pen with what's called "keyboard traps" (demo and editable Pen). As long as the modal window is active, the focus remains within the modal window, as you can see in this screen recording.
If you compare the first and last Pens, you will find that there is not a lot of extra code. It may not be perfect, but the final solution is much better to use.
There is also an example of accessing modal windows and a good article titled "Using tabindex", written by people at Google. If you want to learn more about keyboard testing, please visit the WebAIM website. They provide a list of “the most common online interactions, standard keys for interactions, and other information to be considered during testing.”
For more examples of focus management, check out Marcy Sutton's egghead.io video "Focus Management with CSS, HTML, and JavaScript" or Rob Dodson's A11ycasts episode "What is focus?" 》.
If you need a button, use the <button></button>
element
I have written about buttons in my first post, but obviously a lot of people use universal elements as buttons. Therefore, I think it would not hurt to write something more about this topic.
I created a Pen (debug mode/pen with code) to illustrate some issues with using <div> or <code><span></span>
as buttons instead of <button></button>
or <input type="button">
elements. If you browse the page, you will find that you can focus on the first button, but not the second button. The reason is of course - the first button is <button></button>
and the second button is <div>. You can solve this problem by adding <code><div> to <code>tabindex="0"
, which makes the initially unfocusable elements focusable. This is why the third and fourth buttons are focused, even if they are <div>.
<pre class="brush:php;toolbar:false"><code class="language-html"><h2 tabindex="0">一个可聚焦的标题</h2></code></pre>
<p> Even if you add the button's character, the "div-button" is indeed focused, but it still acts like a <code><div>. To illustrate this, I added a simple click event handler (Pen) to all <code>.btn
elements. If you click the button, an alarm box will pop up, but if you try to do the same with the key (Enter or Spacebar), only the first button will trigger the event. You have to add a key event handler to the "div-button" to fully simulate the default button behavior, which seems like unnecessary overhead, doesn't it? That's why if you need a button, you should use the <button></button>
element. Watch Rob Dodson's A11ycasts episode "Just use button" or read Adrian Roselli's Links, Buttons, Submits and Divs, Oh my God" for more details and examples.
Screen reader users must be notified when content changes dynamically
Usually, screen readers will announce content only when the element gets focus or when the user uses the screen readers' own navigation commands. If the content is loaded dynamically and inserted into the DOM, only the eyesighted person can notice these changes. ARIA real-time zones provide several solutions to this problem. I'll show you how to do it with an example.
Suppose you have a profile settings page where you can edit personal data and save it. When the save button is clicked, the changes are saved without reloading the page. An alert will notify the user whether the change is successful. This may happen immediately and may take some time. I recorded a short video to show you what I just explained.
You can see that the operation is successful, but you can't hear it. Screen reader users won't notice the changes, but there is an easy solution to this problem. By adding a Status or Alert role to the message box, the screen reader will listen to updates in the element.
<code class="language-javascript">function showModal() { var modal = document.getElementById('modal2'); modal.focus(); ... }</code>
If the message text changes, the new text will be read out. You can see and hear how it actually works in this video and see the code in this Pen.
Treat your users with courtesy
The difference between "status" and "alert" is that "alert" interrupts the screen reader when it is announcing something else. Instead, "Status" will wait for the screen reader to complete announcement.
There is also an attribute called aria-live
which can take three possible values: off, polite, or assertive. Of these three values, off is the default value, aria-live="polite"
is equivalent to role="status"
, and aria-live="assertive"
is equivalent to role="alert"
. In some well-known predefined cases, it is best to use a specific provided "real-time zone role". Additionally, if the browser does not support roles, you may need to try to use both properties at the same time. Léonie Watson shared some test results in Screen Reader Support for ARIA Real-Time Zones.
<code class="language-html"><h2 tabindex="0">一个可聚焦的标题</h2></code>
Sometimes it makes sense to declare that it is not just changed
By default, screen readers only display the changed content, even if there is something else in the same real-time area, it makes sense to announce the entire text in some cases. The default behavior can be changed using the aria-atomic
attribute. If set to true, assistive technology will display the entire contents of the element.
Paul J. Adam has a aria-atomic
test case demonstration that compares different real-time locales. He also tested his demo with VoiceOver on iOS 8.1 and recorded so you can see how it actually works. If you want to better understand the possible use cases of aria-atomic
, I suggest you watch the recording (VoiceOver iOS 8.1 reads the remaining characters aria-atomic
and aria-relevant
in the aria-live
area).
Some things to consider
Of course, Rob Dodson also has an A11ycasts episode about details and examples, Alert! 》. Heydon Pickering has another live area example in his ARIA sample collection.
You don't have to guess what usage patterns your component must provide
It is often difficult to think of all the features a component must provide in terms of navigation and accessibility. Fortunately, there is a resource called WAI-ARIA Authoring Practices 1.1 that can help us do this. WAI-ARIA Authoring Practices is a guide to learning how to create accessible rich internet applications using WAI-ARIA. It describes the recommended WAI-ARIA usage pattern and introduces the concepts behind it.
They have guides for building accordion, sliders, tabs, and more.
Accessible JavaScript Components
Here are some excellent resources for accessible JavaScript components:
If you know of any other resources, please share them in the comments.
Summary
Use the advantages of JavaScript to improve accessibility of your website. Pay attention to focus management, understand common usage patterns, and consider screen reader users when operating DOM. Most importantly, don't forget who you made the website for and have fun in the production process.
Beyond
It's all here for the time being. I hope these tips help you write more accessible HTML and JavaScript. Thanks a lot to Heydon Pickering, because his book Inclusive Front-End Design Pattern is the basis for most of what you just read. If you want to learn more about accessibility and inclusive design, I highly recommend reading his book.
Special thanks to Adrian Roselli for helping me write this article, and Eva proofreading my writing.
Resources
This is a list of all linked resources in this article.
FAQs on writing accessible JavaScript
What is the importance of writing accessibility JavaScript?
Writing accessibility JavaScript is crucial because it ensures that your website or application is available to everyone, including people with disabilities. This not only broadens your user base, but also enhances user experience and satisfaction. In many areas, this is also important for legal compliance, as accessibility is required by various disability discrimination bills.
How to make my JavaScript code more accessible?
There are several ways to make your JavaScript code more accessible. First, make sure your website or app is keyboard friendly. This means that users should be able to navigate your website using only the keyboard. Second, make sure your website is easy to navigate with a screen reader. This can be achieved by using semantic HTML and ARIA roles. Finally, always provide alternative text for the image and make sure your website has sufficient color contrast.
What is ARIA and how does it improve accessibility?
ARIA stands for Accessible Rich Internet Applications. It is a set of properties that define methods to make web content and web applications more accessible to people with disabilities. ARIA helps in developing dynamic content and advanced user interface controls using Ajax, HTML, JavaScript and related technologies. It can improve accessibility by providing additional information about elements, their roles, and their current state.
How does keyboard navigation enhance accessibility?
Keyboard navigation is essential for users who cannot use the mouse or touch screen. By ensuring that all features of the website or app are accessible using the keyboard only, you can make your website more susceptible to users with movement or vision impairment. This can be achieved by using tabindex
and focus management in JavaScript code.
What is the role of semantic HTML in accessibility?
Semantic HTML refers to the use of HTML tags to enhance the semantics or meaning of content. For example, use the <button></button>
label for a button instead of a style to make it look like a button. This is important for accessibility because it provides meaningful information for screen readers to help visually impaired users understand content and navigate the website.
How to ensure sufficient color contrast for accessibility?
Enough color contrast is important for users with visual impairment. You can ensure this by choosing a color combination that complies with the WCAG 2.1 Contrast Ratio Guide. There are some online tools that can help you check the contrast ratio of your selected color.
What is the importance of providing image alternative text?
Providing alternative text to images is essential for visually impaired users who rely on screen readers. Alternative text should accurately describe the image content so that users who cannot see the image can still understand their purpose in the page context.
How to test the accessibility of JavaScript code?
There are several tools available to test the accessibility of JavaScript code. These tools include automated testing tools such as aXe and Lighthouse, as well as manual testing using screen readers and keyboard-only navigation. It is important to use a combination of automated testing and manual testing to ensure full accessibility.
What are some common accessibility issues in JavaScript?
Some common accessibility issues in JavaScript include lack of keyboard accessibility, insufficient color contrast, lack of alternative text for images, and lack of ARIA characters or incorrect use of ARIA characters. These issues may make your website difficult or unavailable to use by people with disabilities.
How to learn more about JavaScript and accessibility?
There are many resources to help you learn more about JavaScript and accessibility. These resources include online tutorials, courses and documents from organizations such as W3C. Additionally, practicing writing accessible code and regularly testing accessibility can greatly improve your understanding and skills.
The above is the detailed content of Writing JavaScript with Accessibility in Mind. For more information, please follow other related articles on the PHP Chinese website!