How to continue playing sound when holding key? - javascript

I have a sound in JavaScript that plays when you press the up arrow key.
I would like to have the sound play when you hold the up arrow key, then pause when you release the key.
This is my code now:
var clickSound = new Audio("img/hartslag.mp3");
document.body.onkeyup = function (e){
if(e.keyCode == 38){
clickSound.play();
}
}

You would need to listen to 2 different events. Play on key down and pause on key up.
var clickSound = new Audio("img/hartslag.mp3");
var playing = false;
document.body.onkeydown = function (e){
if(e.keyCode == 38 && !playing){
clickSound.play();
playing=true;
} }
document.body.onkeyup = function (e){
if(e.keyCode == 38){
clickSound.pause();
playing=false;
} }
Code is not tested!

Related

How to track clicks of one button and then another?

I need to track the click on capslock and then the keyboard shortcut ctrl + alt, that is, first click on capslock and then on the keyboard shortcut here is an example
if (e.code == "CapsLock") {
if (e.ctrlKey && e.keyCode == 18) {
alert();
}
}
but this code does not work
I use a function like this:
document.addEventListener("keydown", function (e) {
var caps = e.getModifierState && e.getModifierState('CapsLock'); // true if pressed, false if released
document.onkeyup = function(event) {
if(caps === true){
/** Validate keys are to be processed */
var keycode = event.which;
// works off course only if ctrl key is kept pressed during key stroke = normal behavior in most OS
// Should it work like a ctrl-Lock function you have to work with a state variable
if ((event.ctrlKey === true) && (keycode === 18)) {
alert();
}
else{
/** Let it happen, don't do anything */
return;
}
}
};
});

Multiple keyup events in one JS FILE

I have a JS file for my HTML web page. I want to have 4 things to check. If they hit a number, 1-4 on the keypad, it takes them to a specified url. The script works, but only if I have one.
When I put all 4 events in the js file, only the last one/most recent one works. Is there some kind of syntax that I'm doing wrong that's stopping all of 4 them from working?
To further explain, using this code, only this part of the script runs:
//If they hit keypad number 4
document.body.onkeyup = function(e){
if(e.keyCode == 52){
window.location.href = "foo";
JS:
//If they hit keypad number 1
document.body.onkeyup = function(e){
if(e.keyCode == 49){
window.location.href = "http://localhost:1337/trail";
}
}
//If they hit keypad number 2
document.body.onkeyup = function(e){
if(e.keyCode == 50){
window.location.href = "foo";
}
}
//If they hit keypad number 3
document.body.onkeyup = function(e){
if(e.keyCode == 51){
window.location.href = "http://localhost:1337/topten";
}
}
//If they hit keypad number 4
document.body.onkeyup = function(e){
if(e.keyCode == 52){
window.location.href = "foo";
}
}
If you put all your condition into the same function it will work great. Otherwise you will overwrite your function every times. That is why you got the issue where the only event working was the last one. Last thing, try to use if and then else if. Otherwise you will verify every conditions every single times for no reason.
//If they hit keypad number 1
document.body.onkeyup = function(e){
if(e.keyCode == 49){
window.location.href = "http://localhost:1337/trail";
}
else if(e.keyCode == 50){
window.location.href = "foo";
}
else if(e.keyCode == 51){
window.location.href = "http://localhost:1337/topten";
}
else if(e.keyCode == 52){
window.location.href = "foo";
}
}
This behavior can be explained in this way: What you were trying to do is to assign a function to the onkeyup event. This happens on a same way as when working with variables. Let's say
var key = 1;
is a "reduced" code for
document.body.onkeyup = function(e){
// action for keypad 1
}
then, when assigning another event handling function to your onkeyup, you are doing
key = 2;
Ask yourself a question: does the variable key hold 1? No. That is being overwritten by the above statement. key holds 2 now. The 1 is "lost". That is the reason why the last event handler (for keypad 4) is being executed only. The last assignment has overwritten the previous assignment.
To work around this, you have two options:
group the event actions in one function
use EventTarget.addEventListener
With option 1, you can group your actions in one function like in the interactive example here below:
// input acts as your document.body
const inp = document.getElementById('foo');
inp.onkeyup = function(e) {
if(e.keyCode == 49) {
console.log('pressed keyCode 49'); // press 1
}
else if(e.keyCode == 50) {
console.log('pressed keyCode 50'); // press 2
}
else if(e.keyCode == 51) {
console.log('pressed keyCode 51'); // press 3
}
else if(e.keyCode == 52) {
console.log('pressed keyCode 52'); // press 4
}
};
<input id="foo" type="text" placeholder="type something">
Yet sometimes that is not flexible. Maybe you want to have two different actions to the keyup event. Of course you can group that in one function but what if another js file overwrites the function? Or another snippet further in the js file? That is not productive.
To prevent this, you can use option 2: .addEventListener which is a more robust approach. Here below is an interactive example:
// input acts as your document.body
const inp = document.getElementById('foo');
inp.addEventListener('keyup', function(e) {
if(e.keyCode == 49) {
console.log('first function: keyCode 49'); // press 1
}
});
inp.addEventListener('keyup', function(e) {
if(e.keyCode == 50) {
console.log('second function: keyCode 50'); // press 2
}
});
<input id="foo" type="text" placeholder="type something">
Also, I want to add another suggestion: you were using .keyCode which is deprecated. You can still use but it is not encouraged. It is possible that the browser developers decide to drop this in the future. That leads to a not functioning code.
The problem is that each browser/OS has their own keyCodes which makes it less reliable.
For a clean approach, please consider to use KeyboardEvent.code
Hi and welcome to StackOverflow ;)
You are registering a new onkeyup event listener every time. Try putting the if statements all into one listener like this:
//If they hit keypad number 1
document.body.onkeyup = function(e){
if(e.keyCode == 49){
window.location.href = "http://localhost:1337/trail";
}
if(e.keyCode == 50){
window.location.href = "foo";
}
if(e.keyCode == 51){
window.location.href = "http://localhost:1337/topten";
}
if(e.keyCode == 52){
window.location.href = "foo";
}
}
I hope this helps.
Most people's answer will work however to simply avoid code duplication and a tirade of 'IF' statements, I would just use a switch statement as so :
document.body.onkeyup = function(e){
switch(e.keyCode) {
case 49:
window.location.href = "http://localhost:1337/trail";
break;
case 50:
window.location.href = "foo";
break;
case 51:
window.location.href = "http://localhost:1337/topten";
break;
case 52:
window.location.href = "foo";
break;
}
}
You are overriding the event handler, you need to have one function there. try this option:
//If they hit keypad number 1
document.body.onkeyup = function(e){
if(e.keyCode == 49){
window.location.href = "http://localhost:1337/trail";
} else if(e.keyCode == 50){
window.location.href = "foo";
} else if(e.keyCode == 51){
window.location.href = "http://localhost:1337/topten";
} else if(e.keyCode == 52){
window.location.href = "foo";
}
}
Or you can use a switch instead.
Yes, there is an alternate syntax that allows for multiple event handlers to be added to the same object with out overriding one another.
addEventListener('keyup', functionHere );
/*
// This will work without overriding other functions...
//If they hit keypad number 1
document.body.addEventListener("keyup", function(e){
if(e.keyCode == 49){
window.location.href = "http://localhost:1337/trail";
}
});
//If they hit keypad number 2
document.body.addEventListener("keyup", function(e){
if(e.keyCode == 50){
window.location.href = "foo";
}
});
//If they hit keypad number 3
document.body.addEventListener("keyup", function(e){
if(e.keyCode == 51){
window.location.href = "http://localhost:1337/topten";
}
});
//If they hit keypad number 4
document.body.addEventListener("keyup", function(e){
if(e.keyCode == 52){
window.location.href = "foo";
}
});
*/
// It may be best to combine them all even when using this method...
document.body.addEventListener("keyup", function(e) {
//If they hit keypad number 1
if (e.keyCode == 49) {
window.location.href = "http://localhost:1337/trail";
}
//If they hit keypad number 2
if (e.keyCode == 50) {
window.location.href = "foo";
}
//If they hit keypad number 3
if (e.keyCode == 51) {
window.location.href = "http://localhost:1337/topten";
}
//If they hit keypad number 4
if (e.keyCode == 52) {
window.location.href = "foo";
}
});
Maybe add all your ifs inside one event listener:
document.body.addEventLister("keydown", function(e) {
if (e.key == "Digit1") {
window.location.href = "http://localhost:1337/trail";
}
if (e.key == "Digit2") {
window.location.href = "foo";
}
if (e.key == "Digit3") {
window.location.href = "http://localhost:1337/topten";
}
if (e.keyCode == "Digit4") {
window.location.href = "foo";
}
}

The keyPressed function only fires once for each key in Chrome

I am using the P5 library and I want to register key presses. Everything runs as expected on Chrome,Edge and Firefox when the HTML file is opened locally. If I try to host it on github pages it works on Firefox and Edge, but unfortunately not on Chrome. I have tried writing to the console when the keyPressed function detects a key press, which should happen every time a key is pressed, but it only registers the arrow keys once and then ignores they following key presses. Does anyone have a clue about what might be causing this.
function keyPressed(){
if(keyCode === 37){
MoveLeft();
}
if(keyCode === 38){
MoveUp();
}
if(keyCode === 39){
MoveRight();
}
if(keyCode === 40){
MoveDown();
}
if(gameOver === true){
ResetGame();
}
console.log('keyPressed');
return false;
}
var bg = "#333";
var gameover = false;
function draw() {
background(bg);
}
function keyPressed(){
if(gameover){return false;}
if(keyCode === 32){
bg = "#0000FF";
}
return false;
}
function keyReleased(){
bg = "#333";
}
See https://p5js.org/reference/#/p5/keyCode
Use http://keycode.info/

in keydown event when press key(40),(38),(13) any of them, then immediately other function will stop.and current function will start

if i press any key of them (38)(40)(13) then immediately other function will stop.and current function will start.like if i press key(40) then function verticalSlideUp() will start.after that if i press key (38) then immediately function verticalSlideDown() will be start.and this verticalSlideUp() function will be stop.
i need help to do this.
This is my jsfiddle.net code here
here is my js code :
var allowed = true;
$(document).keydown(function (e) {
if (e.repeat != undefined) {
allowed = !e.repeat;
}
if (!allowed) return;
allowed = false;
if (controlsEnabled)
{
if (e.keyCode == 38) {
allowed = true;
verticalSlideDown();
console.log("pressed key for Down : "+e.keyCode);
}
if (e.keyCode == 40) {
allowed = true;
verticalSlideUp();
console.log("pressed key for Up: "+e.keyCode);
}
if (e.keyCode == 13) {
allowed = true;
var div= $(".scroll-inner-container");
console.log("pressed key for stop : "+e.keyCode);
div.stop();
}
}
});
I assume those slide functions have some infinite loop. Maybe you can try to have some variable like functionFired and at the beginning of function setting some value and if that loop detects change it will break.

Return true if key is down in javascript loop?

I want to add a condition inside a loop that tests if the right arrow is pressed and if it is move a div a bit to the right. However I don't know how to check for they keydown.
I'm using a code to do it but it is really long and I'm sure there is an shorter way to do it.
This is the code:
<div id="char"></div>
<script>
setInterval(function() {
// here it should check if RIGHT (keycode 39) is down and move char 10px to the right if it is;
}, 20);
</script>
How can I check for keydown inside the loop? Btw I'm also using jQuery on the site.
Thanks
Here ya go in raw JS you'd do something like this (press Preview then hold down w):
http://jsbin.com/odalo3/edit
var isPressed = false;
var keydown = function(e){
if(e.keyCode == 87){
isPressed = true;
}
}
var keyup = function(e){
isPressed = false;
}
document.addEventListener("keydown",keydown,false);
document.addEventListener("keyup",keyup,false);
setInterval(function(){
if(isPressed){
document.getElementById('hello').innerHTML = document.getElementById('hello').innerHTML+', pressed';
}
},100)
UPDATE
If you are using jQuery you can change the eventListeners to:
$(window).keydown(function(e){
if(e.keyCode == 87){
isPressed = true;
}
})
.keyup(function(e){
isPressed = false;
})
And delete these lines:
var keydown = function(e){
if(e.keyCode == 87){
isPressed = true;
}
}
var keyup = function(e){
isPressed = false;
}
document.addEventListener("keydown",keydown,false);
document.addEventListener("keyup",keyup,false);
But it's the same thing.
Use jQuery and keydown:
<div id="char"></div>
<script>
$(document).keydown(function(e){
if(e.keyCode == 39){
//do something
$("#char").animate({'left':'+=10'}, 1);
}
})
</script>
Fiddle: http://jsfiddle.net/maniator/zXeXt/
Create a flag var pressed; and set it to true or false in keyPress event; then check it inside the loop

Categories

Resources