Given a part of a function, that works perfectly when the left mouse is clicked (toggles the play/pause perfectly functional). However, when using a keyboard only browsing method using the tab key, the button gets selected with the tab but pressing the enter
or the spacebar
doesn't play or pause the audio, so the toggle is not accessible by keyboard. Since the play button starts the screenreader for the visually impaired/blind, and blind people do not use a mouse, this key must be pressed using a keyboard only method: a spacebar or an enter. How to implement those two keystrokes alongside the currently working left mouse button sothat instead of one trigger, all three triggers play and pause the screen reader? Thanks, on behalf of future blind users without a mice.
// starts the screen reader
play.addEventListener('click', function() {
myAudio.play();
});
// pauses the screen reader
pause.addEventListener('click', function() {
myAudio.pause();
});
jsfiddle demo works with mouseclick but not an Enter/ Spacebar keypress
Note: This answer has been edited for accuracy.
After reading OP's comment, this is the solution to their problem.
Your new HTML:
<audio src="http://labs.qnimate.com/files/mp3.mp3"></audio>
<play tabindex="1">PLAY</play>
<pause tabindex="1">PAUSE</pause>
Your new CSS:
play, pause {
display: none;
text-align:center;
vertical-align:middle;
width: 200px;
height: 50px;
font-size: 30px;
background: yellow;
cursor: pointer;
}
play:focus, pause:focus { /* TABBED BROWSING */
outline: 2px solid #00F;
}
Your new JavaScript:
var myAudio = document.getElementsByTagName('audio')[0];
var play = document.getElementsByTagName('play')[0];
var pause = document.getElementsByTagName('pause')[0];
function displayControls() {
play.style.display = "block";
}
// check that the media is ready before displaying the controls
if (myAudio.paused) {
displayControls();
} else {
// not ready yet - wait for canplay event
myAudio.addEventListener('canplay', function() {
displayControls();
});
}
play.addEventListener("keyup", function(event) {
let KEY = event.code;
if (KEY === "Enter" || KEY === "Space") { // Space or Enter pressed.
myAudio.play();
play.style.display = "none";
pause.style.display = "block";
pause.focus(); // This is very important. Without it the UI breaks.
}
});
pause.addEventListener("keyup", function(event) {
let KEY = event.code;
if (KEY === "Enter" || KEY === "Space") { // Space or Enter pressed.
myAudio.pause();
pause.style.display = "none";
play.style.display = "block";
play.focus(); // This is very important. Without it the UI breaks.
}
});
play.addEventListener('click', function() {
myAudio.play();
play.style.display = "none";
pause.style.display = "block";
});
pause.addEventListener('click', function() {
myAudio.pause();
pause.style.display = "none";
play.style.display = "block";
});