This is what I thought should work but it doesn't. I'm am using unicode 112 for the "p" key and 115 for "s".
var audio = document.getElementById("lessonTrack");
window.addEventListener("keypress", playPauseKb, false);
function playPauseKb() {
var x = event.keycode;
if (x == 112) {
audio.play();
}
else if (x == 115) {
audio.pause();
}
}
You had the right idea. I added some debugging steps that you can take in the future to help you trouble shoot your code. You just have to remove the comments for testing. I also added the missing event parameter to your function. I changed the event to keyup but you can use another event if you choose, however some keyboard buttons will not respond to key down events.
You should also try and get in the habbit of using === instead of == when you can it will help prevent some possible bugs in the future. The == operator will match the value but the === operator will match the value and type. This can be a problem if you want to make sure your value is a string,number,etc.
Update: You might want use the following line of code in place of the original line to check for keypress events in firefox because it will return 0 for event.keyCode.
//check to see which event property is supported
var x = event.which || event.keyCode;
JavaScript:
var audio = document.getElementById("lessonTrack");
window.addEventListener("keyup", playPauseKb, false);
function playPauseKb(event) {//<-- added missing event parameter
var x = event.keyCode;
//debug
//console.log(x);
//p on the keyboard
if (x === 80) {
audio.play();
//alert("playing");
} else if (x === 83) { //s button keycode
audio.pause();
//alert("paused");
}
}
Try the following: Looks like you have the wrong call to keyCode, javascript is case sensitive so keycode is not the same as keyCode
var audio = document.getElementById("lessonTrack");
window.addEventListener("keydown", function(e) {
var x = e.keyCode;
if (x === 80) { // pressed 'p'
audio.play();
} else if (x === 83) { // pressed 's'
audio.pause();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With