Hi guys, I need your help, I have a problem with my javascript where I am trying to access to another javascript file to get things right and working but it is not working when I press on the keyboard up and down arrow buttons. here is the html code: <html> <body> <style type="text/css"> body {background:url('/images/blue_background.jpg') no-repeat center center fixed;} </style> <body style="overflow: hidden"> <script> <script type="text/javascript" src="test.js"></script> <script type="text/javascript"> </script> </body> </html> Code (markup): here is the test.js file document.onkeydown = checkKey; function checkKey(e) { if(key == 38) { alert('up arrow are working'); } if(key == 40) { alert('down arrow are working'); } Code (markup): Any advice would be much appreicated. thanks in advance
You are missing a LOT of code in your checkkey function... like your KEY variable is never defined, you don't evaluate for e (so it's not cross-browser code), etc, etc... it's also 'sloppy' to use the onkeydown hook on document... that should be done with addEventListener or attachEvent just in case something else wants to hook onto it as well. Likewise multiple if statements of the same value are often inefficient -- more so if you add more keypress traps, which is why you should be using a SWITCH there instead. function checkKey(e) { e=e || window.event; var key = e.charCode || e.keyCode || e.which; switch (key) { case 38: alert('up arrow is working'); break; case 40: alert('down arrow is working'); break; } } if (document.addEventListener) { document.addEventListener('keydown',checkKey,false); } else { document.attachEvent('onkeydown',checkKey); } Code (markup): Also, there is no legitimate reason to EVER set overflow:hidden on body, since that results in no scrollbars for the page EVER, aka an accessibility train wreck. You should also probably be testing WITH a doctype, since that can change the behavior of javascript across different browsers. (including some non-IE ones -- everyone talks about docype as a layout trigger, but rarely what it does to scripting) Oh, and that second empty script in the markup -- don't know what that is, but it's unnecessarily.