This tutorial will guide you through the process of creating a Toggle Switch With Accessibility In Javascript. An accessible toggle switch enhances user experience by providing clear visual and semantic cues for interaction, making it usable for everyone, including users with disabilities who rely on assistive technologies.
Prerequisites
Before you start, you should have a basic understanding of HTML, CSS, and JavaScript.
Step 1: Create the HTML Structure
We’ll start by creating the HTML structure for our toggle switch. This structure is based on the inclusive-components.design example to ensure accessibility.
<!-- Based on https://inclusive-components.design/toggle-button/ -->
<span class="toggle-button-wrapper">
<span>inc vat</span>
<button role="switch" aria-checked="false" aria-label="show vat off">
<span class="accessibility">show vat</span>
<span class="toggle-button-switch"></span>
</button>
<span>ex vat</span>
</span>
<script src="./script.js"></script>
Step 2: Style the Toggle Switch with CSS
Now, let’s add some CSS to style the toggle switch. This will define the appearance of the switch and its various states.
* {
box-sizing: border-box;
}
.accessibility {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
.toggle-button-wrapper {
font-family: sans-serif;
font-size: 1em;
font-weight: normal;
line-height: 35px;
}
.toggle-button-wrapper * {
display: inline-block;
vertical-align: middle;
}
[role="switch"] {
background-color: #000;
border: 0.062em solid #000;
border-radius: 25px;
color: #fff;
cursor: pointer;
display: inline-block;
height: 35px;
margin: 0 5px;
overflow: visible;
padding: 5px;
position: relative;
width: 70px;
}
[role="switch"]:focus {
outline: 3px dashed darkolivegreen; /* temp style to show focus state in POC */
}
.toggle-button-switch {
background: #ffd800;
border-color: #ffd800;
color: #000;
border: 1px solid #000;
border-radius: 50%;
display: inline-block;
height: 25px;
right: 5px;
line-height: 25px;
position: absolute;
top: 5px;
width: 25px;
}
[role="switch"][aria-checked="true"] .toggle-button-switch {
left: 5px;
}
Step 3: Implement the JavaScript Functionality
Next, we’ll add JavaScript to handle the toggle functionality and update the aria-label for accessibility.
var toggle = document.querySelector('[aria-checked]'),
$this,
pressed,
label;
toggle.addEventListener('click', function(e) {
$this = e.target;
pressed = $this.getAttribute('aria-checked') === 'true';
$this.setAttribute('aria-checked', !pressed);
label = $this.textContent.trim();
if (!pressed) {
$this.setAttribute('aria-label', label + ' on');
} else {
$this.setAttribute('aria-label', label + ' off');
}
});
Conclusion
You have now successfully created a toggle switch with accessibility in JavaScript. This toggle switch is not only functional but also provides a better experience for all users, including those who rely on assistive technologies.







