I'm currently building a music player with three buttons (actually simple divs) for Play/Pause (id="play"), Previous (id=rew) and Next (id="fwd").
I want the Play/Pause to be "clicked" when pressing SPACEBAR.
I want the Previous to be "clicked" when pressing LEFT ARROW.
I want the Next to be "clicked" when pressing RIGHT ARROW.
I've successfully managed the SPACEBAR control of Play with this :
var play = document.getElementById("play");
document.onkeydown = function (e) {
if (e.keyCode == 32) {
play.click();
}
};
However, when I add the same for the two other buttons in my script, the SPACEBAR control of Play does not work anymore, as well as the other two.
So, what I have currently in my script and which is obviously not working is this :
<script>
var play = document.getElementById("play");
document.onkeydown = function (e) {
if (e.keyCode == 32) {
play.click();
}
};
var rew = document.getElementById("rew");
document.onkeydown = function (e) {
if (e.keyCode == 37) {
rew.click();
}
};
var fwd = document.getElementById("fwd");
document.onkeydown = function (e) {
if (e.keyCode == 39) {
fwd.click();
}
};
</script>
What am I doing wrong ?
Each of your keydown events is overwriting the previous one.
Instead, put all the logic into one keydown event, like this:
var play = document.getElementById("play");
var rew = document.getElementById("rew");
var fwd = document.getElementById("fwd");
document.onkeydown = function(e) {
if (e.keyCode == 32) {
play.click();
} else if (e.keyCode == 37) {
rew.click();
} else if (e.keyCode == 39) {
fwd.click();
}
};
When you assign to onkeydown several times only the last one will be assigned because it will override the previous one. You can use addEventListener instead but that isn't the best approach neither. Just make more test inside one event listener like this:
var play = document.getElementById("play");
var rew = document.getElementById("rew");
var fwd = document.getElementById("fwd");
document.onkeydown = function (e) {
if (e.keyCode == 32) {
play.click();
}
else if(e.keyCode == 32) {
rev.click();
}
else if(e.keyCode == 32) {
fwd.click();
}
};
Related
l have 2 functions, l want to do like when the first keydown run one function than if its another keydown run the second function!
It is play/pause video function by spaceBar!
document.addEventListener('keydown', function(e) {
if (e.keyCode == 32) {
pauseAllVideos();
} else {
playAllVideos();
}
});
Solution
Its all about saving a boolean value that lets you know if all videos are playing or not and then use it in the if statements.
Here is the code snippet:
let playing = false;
const playAllVideos = () => console.log('playing all videos');
const pauseAllVideos = () => console.log('paused all videos');
const playPause = e => {
let key = e.keyCode || e.which;//Get key
if(key == 32) { //Space key
if(playing) {//If playing turn all videos off
pauseAllVideos();
playing = false;
} else {//vise versa
playAllVideos();
playing = true;
}
}
}
window.addEventListener('keypress', playPause);
<p>Press Space</p>
I tried with this code to detect two keyboard arrows being simultaneously pressed:
document.addEventListener('keydown', event => {
if (event.keyCode === 38) {
console.log('up Arrow')
}
if (event.keyCode === 39) {
console.log('right Arrow')
}
})
But it doesn't work, however hard I try to press them at exactly the same time.
How can I cleanly fix this and detect when both keys are down ?
There's only one keyCode per event. You have to track the keys going down, and up:
// if you keep both up and down keys down, you'll get a message
let downKeys = {}; // the set of keys currently down
document.addEventListener('keydown', event => {
downKeys[event.keyCode] = true;
if (downKeys[38] && downKeys[40]) {
console.log("both down!");
}
});
document.addEventListener('keyup', event => {
downKeys[event.keyCode] = false;
});
(you have to go full page to test this snippet)
Here I use 2 flags to check if you are holding the keys.
If both flags are true then it means that you are holding both keys. So, you can perform anything inside the condition.
let holdKeyUp = false;
let holdKeyRight = false;
document.addEventListener('keydown', event => {
if (event.keyCode === 38) {
holdKeyUp = true;
}
if (event.keyCode === 39) {
holdKeyRight = true;
}
if (holdKeyUp && holdKeyRight) {
console.log("Both keys are pressed.");
}
})
document.addEventListener('keyup', event => {
if (event.keyCode === 38) {
holdKeyUp = false;
}
if (event.keyCode === 39) {
holdKeyRight = false;
}
})
in the code below i'm trying to get it to log "success" into the console when I press the "w" button, but for some reason it's not doing anything when I press it. can someone tell me what I'm doing wrong?
var keysDown = {};
var keysUp = {};
window.addEventListener('keydown', function(e) {
keysDown[e.keyCode] = true;
});
window.addEventListener('keyup', function(e) {
delete keysDown[e.keyCode];
keysUp[e.keyCode] = true;
});
if (37 in keysDown || 65 in keysDown) { //left
console.log("success");
}
window.addEventListener('keyup', function(e) {
console.log(e.keyCode)
if(e.keyCode == 37 || e.keyCode == 65) console.log('yay')
});
http://jsfiddle.net/zackify/anq34vsv/ Just check for the keycode in the event listener function.
So I have a game, and Im trying to keep it from starting unless the user pressed the Enter key.
This is the code I have for that:
var code = (e.keyCode ? e.keyCode : e.which);
var enterpressed = 0;
do {
if(code == 13) { //Enter keycode
enterpressed = 13;
}
ctx.font = "25px Helvetica";
drawStartScreen();
update();
} while (enterpressed === 13);
This is the full program, on JSfiddle:
http://jsfiddle.net/3aoozxte/6/
Edit: I figured it out!
Here is the program working:
http://jsfiddle.net/84c2k5kg/6/
Here is the solution to your problem.
I added the enter key logic to your keydown eventlistener. So when you press enter it starts the game.
I deleted the loop in startGameScreen() to prevent the browser crashing repeating this infinite loop.
http://jsfiddle.net/3aoozxte/19/
function main() {
canvas = document.createElement("canvas");
canvas.width = COLS*20;
canvas.height = ROWS*20;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
ctx.font = "12px Helvetica";
frames = 0;
keystate = {};
started = false;
// keeps track of the keyboard input
document.addEventListener("keydown", function(evt) {
keystate[evt.keyCode] = true;
if(keystate[Key_ENTER] && !started) { // Start the game if it's not started and Enter is pressed.
started = true;
init();
loop();
}
});
document.addEventListener("keyup", function(evt) {
delete keystate[evt.keyCode];
});
//Attempting to create a welcome screen
startGameScreen();
}
function startGameScreen() {
ctx.font = "25px Helvetica";
drawStartScreen();
}
This might be the one you are looking for.
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.ctrlKey && evt.keyCode == 90) {
alert("Ctrl-Z was pressed");
}
else {
var kc = evt.keyCode
switch(kc){
case 13 : alert("Enter was pressed"); break
case 37 : alert("Left Key was pressed"); break
case 38 : alert("Up Key was pressed"); break
case 39 : alert("Right Key was pressed"); break
case 40 : alert("Down Key was pressed"); break
// default : alert(kc + " was pressed");//used to check for key value
}
}
};
Fiddle Key Events
Adding the function on your listener..
document.onkeydown = function(evt) {
if (evt.keyCode == 13) {
started = true;
init();
loop();
}
}
Updated and working Game
Complete reference Complete Handling Key Events
I prefer using jquery
$(document).keypress(function(e)
{
if (e.which == 13)
{
//Your code
}
});
I've been wondering if there was a simple way to detect if a user presses the same character on the keyboard twice within one second. I've written some code that kind of works but it's unreliable.
var escapeCount = 0;
function reset() {
escapeCount = 0;
setTimeout('reset();', 1000);
}
window.onload = function() {
reset();
};
document.onkeyup = function(e) {
if (!e) var e = window.event;
var code = e.keyCode ? e.keyCode : e.which;
if (code == 27) escapeCount +=1;
if (escapeCount == 2) {
// stuff on second escape
}
};
Is there a better way to do this? Thanks
It would make sense to reset after 1 second has passed since the last character was pressed. Example:
var lastChar = -1;
document.onkeyup = function(e) {
if (!e) var e = window.event;
var code = e.keyCode ? e.keyCode : e.which;
if (lastChar == code) {
// Same key was pressed twice in a row within 1 second.
} else {
lastChar = code;
setTimeout(function() {lastChar = -1;}, 1000);
}
};
Your timer resets every second, so you not only have to press Escape again within a second of the last Escape, but that also has to have no timeout in between the presses.
It's probably easier to forget the timeout and just remember the time of the last keypress instead:
var lastescapetime= null;
document.onkeyup= function(event) {
if (event===undefined) event= window.event;
if (event.keyCode===27) {
var now= new Date().getTime();
if (lastescapetime!==null && now<lastescapetime+1000) {
alert('You double-escaped!');
lastescapetime= null;
} else {
lastescapetime= now;
}
} else {
lastescapetime= null;
}
};