JSFiddle - React, Tailwind, and code Playground
by Artem
HTML
<h1>Some simple name change tests</h1>
<p>Each button under "Tests" dynamically changes its calculated accessible name when clicked, switching between "Pause" and "Play".</p>
<h2>Description</h2>
<ul>
<li>Button 1: changes <code>aria-label</code></li>
<li>Button 2: changes text content</li>
<li>Button 3: changes text in element referenced through <code>aria-labelledby</code></li>
<li>Button 4: no name change, only state change using <code>aria-pressed</code></li>
</ul>
<h2>Tests</h2>
<ol>
<li><button type="button" data-paused="false" aria-label="Pause">⏸</button></li>
<li><button data-paused="false" type="button">Pause</button></li>
<!-- this is not an accessible tooltip; it exists only for the purpose of demoing realistic aria-labelledby changes -->
<li>
<div class="tooltip-container">
<button data-paused="false" type="button" aria-labelledby="tooltip">⏸</button>
<span class="tooltip" id="tooltip">Pause</span>
</div>
</li>
<li><button data-paused="false" type="button" aria-label="Play" aria-pressed="true">⏸</button></li>
</ol>
CSS
body {
font-family: sans-serif;
padding: 2em;
}
button {
font-size: 1.5em;
}
li {
margin-bottom: 1em;
}
.tooltip-container {
display: inline-block;
position: relative;
}
.tooltip {
position: absolute;
top: -100%;
left: 50%;
transform: translate(-50%, 0);
padding: 3px;
background-color: rgba(0, 0, 0, 0.9);
color: #fff;
border-radius: 2px;
opacity: 0;
pointer-events: none;
}
button:hover + .tooltip,
button:focus + .tooltip {
opacity: 1;
pointer-events: all;
}
JavaScript
var buttons = Array.prototype.slice.call(document.querySelectorAll('button'));
buttons.forEach(function(button) {
button.addEventListener('click', function(event) {
var button = event.target;
var isPaused = button.getAttribute('data-paused') === 'true';
var newLabel = isPaused ? 'Pause' : 'Play';
if (button.hasAttribute('aria-pressed')) {
button.setAttribute('aria-pressed', isPaused + '');
button.innerHTML = isPaused ? '⏸' : '▶️';
}
else if (button.hasAttribute('aria-label')) {
button.setAttribute('aria-label', newLabel);
button.innerHTML = isPaused ? '⏸' : '⏯';
}
else if (button.hasAttribute('aria-labelledby')) {
document.getElementById('tooltip').innerText = newLabel;
button.innerHTML = isPaused ? '⏸' : '▶';
}
else {
button.innerHTML = newLabel;
}
button.setAttribute('data-paused', !isPaused + '');
});
});