could someone check over this snippet of javascript please

Associate
Joined
11 Oct 2008
Posts
268
Hey guys, I have this bit of javascript which loads a certain url if the w,a,s,d keys are pressed. Its working fine but a lot of examples I've been looking at include things like break; and addeventlistener.

Mine does not include these things so I just wanted to check my code isn't incomplete or flawed. Thanks guys.

Code:
 <script>
    document.onkeydown = function(e) {
    e = e || window.event;
    key = e.keyCode || e.charCode;
    var keys = { 
      87: '?move=up', 
      68: '?move=right', 
      83: ?move=down', 
      65: '?move=left'
    };
    if (keys[key]) window.location.href = keys[key];
    };
    </script>
 
Associate
Joined
4 Feb 2011
Posts
580
Location
Halifax
It's pretty much another way of writing

Code:
document.addEventListener('keydown', function(){});

Otherwise it looks fine. There's no logical reason to use break here since you're not looping.
 
Last edited:
Associate
OP
Joined
11 Oct 2008
Posts
268
Okay, Sorry to be a pain, how would I implement it into my bit of code.
I know next to nothing with javascript so have been trying a few different ways but they all seem to break the code. Firefoxs debugger isn't showing me any error messages either so I'm at a loss.

Thanks again for all your help.
 
Soldato
Joined
28 Oct 2006
Posts
12,456
Location
Sufferlandria
This line:

document.onkeydown = function(e) {

Could be changed for the code that xbenjiman posted:

document.addEventListener('keydown', function(e){

There's no real reason that you would need to change it in your code - they essentially do the same thing.
 
Back
Top Bottom