I'm trying to work on a, you can say a practice project, In which an audio file will be played in background, Which would be be Paused if SPACEBAR key is pressed and Play when it's pressed again. so, is there anything like onkeypress, keydown etc which can be added to body of html. Thanks, in advance.
Asked
Active
Viewed 57 times
-1
-
Possible duplicate of [action by key press](https://stackoverflow.com/questions/8294876/action-by-key-press) – Ivar Apr 21 '18 at 10:13
-
Possible duplicate of [Trigger a button click with JavaScript on the Enter key in a text box](https://stackoverflow.com/questions/155188/trigger-a-button-click-with-javascript-on-the-enter-key-in-a-text-box) – Nikola Lukic Apr 21 '18 at 10:14
-
Possible duplicate of [execute code after press on spacebar](https://stackoverflow.com/questions/24386354/execute-code-after-press-on-spacebar) – Dineth Cooray Apr 21 '18 at 10:16
-
Nikola Lukic , well thers's nothing like textbox i mentioned. – SparkShredder Apr 21 '18 at 10:21
-
Ivar and Dineth Cooray ,well the links are for my purpose ...thnx – SparkShredder Apr 21 '18 at 10:22
-
Thanks , to.....whoever gifted me -1 ...lol – SparkShredder Apr 21 '18 at 10:23
2 Answers
0
var isplaying = false;
window.addEventListener("keydown", function (e) {
if (e.keyCode === 32) {
if (isplaying) {
//Code for pause
} else {
//Code for play
}
}
});

Abi
- 165
- 1
- 12
-1
You can use a variable to store current state and modify that on key press event as
var state=0; // 0 for play, 1 for pause
document.body.onkeyup = function(e){
if(e.keyCode == 32){
if(state==0)
{
state=1;
//Run your code to pause
}
else{
state=0;
//Run your code to play
}
}
}

Mesar ali
- 1,832
- 2
- 16
- 18