Multiple keyup events in one JS FILE - javascript

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";
}
}

Related

keyup event does not work by pressing shift + a + s [duplicate]

This question already has answers here:
How to detect if multiple keys are pressed at once using JavaScript?
(19 answers)
Closed 3 years ago.
$(document).keyup(function(e) {
if (e.shiftKey && e.keyCode == 65 && e.keyCode == 83) {
url = "https://stackoverflow.com/";
window.location.replace(url);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I made a log function so you can see what key code's are being used. And set it up with the enter key.
document.body.addEventListener('keyup', logKey);
function logKey(e) {
console.log(`KeyCode: ${e.code}`)
if (e.code === 'KeyS' || e.code === 'Enter') {
let url = "https://stackoverflow.com/";
window.location.replace(url);
}
}
As #putvande said you can detect only one key press at a time, a trick i suggest you is to detect multiple keydown combinations, like this:
let shiftkey_press = false;
let A_press = false;
let S_press = false;
document.onkeydown = function(e) {
if (e.shiftKey ) {
shiftkey_press = true;
}
if (e.keyCode == 65 ) {
A_press = true;
}
if (e.keyCode == 83 ) {
S_press = true;
}
console.log("shiftkey_press:", shiftkey_press)
console.log("A_press:", A_press)
console.log("S_press:", S_press)
if (shiftkey_press && A_press && S_press ){
url = "https://stackoverflow.com/";
// window.location.replace(url);
alert(url);
}
}
yeah i know... it's a litle bit nasty, but i think it will do the trik, let me know if it's work please!
A WORKING EXAMPLE: https://jsfiddle.net/b7an8L12/
EDIT:
i just replace your window.location.replace by an alert()
"MAKE SURE TO OPEN THE CONSOLE TO SEE WHAT's HAPPENING!" :-)

delete element using remove() while clicking and pressing a key

I want to add a delete mode that the user can enter by pressing a certain key (Im using the key "enter" for now e.which == 13 checks if the key pressed is enter in the below sample)
var checker = 1;
$(document).keypress(function (e) {
if (e.which == 13 && checker == 1) {
checker = 2;
alert("entered delete mode");
$(".element1").click(function (e) {
$(this).remove();
});
}
else if (e.which == 13 && checker == 2) {
checker = 1;
alert("exited delete mode");
$(".element1").each(function (i, e) {
$(this).off("click", "**");
});
};
});
So basically when the user presses enter I check if we are in the delete mode already, if not (checker ==1) we enter it and I add a function on click() for objects with class ".element1"
If the user is in not in delete mode (checker==2), I try to remove the click method.
But for some reason this part does not work.
Thank you all.
EDIT
I also tried to add .click to the .element class: (this way in my mind it should've deleted the element when I hover and press enter)
$(.element1)
.hover(function (e) {
var deletable = $(this);
$(document).keypress(function (e) {
if (e.which == 13) {
deletable.remove();
}
});
});
but whenever I press enter it just deletes all .elements
Any way works for me.
You can't have a second argument on the .off(). Fixed code:
var checker = 1;
$(document).keypress(function (e) {
if (e.which == 13 && checker == 1) {
checker = 2;
alert("entered delete mode");
$(".element1").click(function (e) {
$(this).remove();
});
}
else if (e.which == 13 && checker == 2) {
checker = 1;
alert("exited delete mode");
$(".element1").off("click");
};
});
I also got rid of the second .each(), as suggested in the comments (it wasn't necessary).
Try using on/off like this and not removing the element:
var checker = 1;
$(document).keypress(function (e) {
if (e.which == 13 && checker == 1) {
checker = 2;
alert("entered delete mode");
$(".element1").on('click', function (e) {
// handle click
});
}
else if (e.which == 13 && checker == 2) {
checker = 1;
alert("exited delete mode");
$(".element1").off('click', '**');
};
});

Keyboard shortcut for hyperlink (jQuery)

I have six links on my webpage (and nothing else) and I would like to number each, 1 to 6. It would be nice to have the client hit corresponding number key without the ctrl and alt, etc.
Is this possible and what would be the best approach with jquery or other html scripts?
Here is one version, for jQuery:
$(document).ready(function() {
$("body").keypress(function(event) {
var link = "#link";
if(event.keyCode == 49) link += 1;
if(event.keyCode == 50) link += 2;
if(event.keyCode == 51) link += 3;
if(event.keyCode == 52) link += 4;
if(event.keyCode == 53) link += 5;
if(event.keyCode == 54) link += 6;
if(link != "#link") $(link).trigger("click");
});
});
Without control + key: keypress event listener in query, and listen for a particular key code per button.
With control + key: You could use an access key (http://www.cs.tut.fi/~jkorpela/forms/accesskey.html)
If you want to do this without the alt or ctrl key you'll need JavaScript. You could attach an event lister to the html or body tag and listen for the keypress event. Don't use complex 'if' statements, that is not necessary. It can be elegant like this (using jQuery):
link1
link2
etc
$('body').keypress(function(e) {
$('[code=' + String.fromCharCode(e.keyCode-48) + ']').click();
});
With the ctrl/alt key you could use the accesskey html attribute: http://reference.sitepoint.com/html/a/accesskey
$('body').bind('keypress', function(e) {
if(e.keyCode==49){ // number 1 on the keyboard been pressed
$('firstHref').click();
} else if(e.keyCode==50) { // number 2
$('secondHref').click();
} else if(e.keyCode==51) { // number 3
$('thirdHref').click();
}else if(e.keyCode==52) { // number 4
$('fourthHref').click();
}else if(e.keyCode==53) { // number 5
$('fiveHref').click();
}else if(e.keyCode==54) { // number 6
$('sixHref').click();
}
});
You can try something like this: Link (click the run button then click inside of the 'Result' box before you hit the numb keys.
$('body').bind('keypress', function(e) {
if(e.keyCode==49){ // 1
alert('1 key pressed');
window.location = "http://www.stackoverflow.com/"
}
if(e.keyCode==50){ // 2
alert('2 key pressed');
window.location = "http://jsfiddle.net/"
}
if(e.keyCode==51){ // 3
alert('3 key pressed');
window.location = "http://www.google.com/"
}
if(e.keyCode==52){ // 4
alert('4 key pressed');
window.location = "http://www.stackoverflow.com/"
}
if(e.keyCode==53){ // 5
alert('5 key pressed');
window.location = "http://jsfiddle.net/"
}
if(e.keyCode==54){ // 6
alert('6 key pressed');
window.location = "http://www.google.com/"
}
});​

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

How to disable Enter/Return Key After a function is executed because of it?

I have this function where #text_comment is the ID of a textarea:
$('#text_comment').live('keypress',function (e) {
if(e.keyCode == 13) {
textbox = $(this);
text_value = $(textbox).val();
if(text_value.length > 0) {
$(this).prev().append('<div id="user_commenst">'+text_value+'</div>');
$(textbox).val("");
}
}
});
What is happening is the text is appending when the enter/return key is hit (keyCode 13), but it is also moving the text a line down, as the enter/return key is supposed to.
This is occurring even though I set the value of the textbox to "".
How about event.preventDefault()
Try and stop your event propagation (See http://snipplr.com/view/19684/stop-event-propagations/) when entering the if(e.keyCode == 13) case.
try this one event.stopImmediatePropagation()
$('#text_comment').live('keypress',function (e) {
if(e.keyCode == 13) {
e.stopImmediatePropagation()
///rest of your code
}
});
I've tested this out, this works. The enter does not create a new line.
$('#text_comment').live('keypress',function (e) {
if(e.keyCode == 13) {
textbox = $(this);
text_value = $(textbox).val();
if(text_value.length > 0) {
$(this).prev().append('<div id="user_commenst">'+text_value+'</div>');
$(textbox).val("");
}
return false;
}
});
Although I am wondering, if you don't want to ever have a new line, why are you using a textarea, why not use a input type='text' instead ?
Answer here http://jsfiddle.net/Z9KMb/

Categories

Resources