Multiple keyup events in one JS FILE

  • A+
Category:Languages

I have a JS file for my HTML webpage. 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 scrip 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";     } }

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: