javascript using key press to load page.

Associate
Joined
11 Oct 2008
Posts
268
Hey guys, I have been looking all round the web and found quite a few tutorials on this, but they are either way over my head, or trying to make code more complex than my needs.

Im trying to find some javascript, or maybe ajax (sorry not too sure which one, never touched js before) that when i press the up arrow button on my keyboard, it loads the page up.php and the same goes for down, right, left etc.

Could anyone help me with this, or reccomend some tutorials if you know any that could help a rookie. Cheers.

edit:

I have this code I found on another forum, I have tried to incorporate this into my page but nothing happens.

Code:
<script>
function pageRedirector(keycode){
  var keyPressToPageMap = {
        37   :  'west',
        38   :  'north',
        39   :  'east',
        40   :  'south'
  };
  
  if(keyPressToPageMap[keycode]){
        window.location = keyPressToPageMap[keycode] + '.php';
  };
 
};
</script>
 
Last edited:
It looks like you havent bound the event. The below should work.

Basically I am binding an anonymous function to a given DOM element (you'll most likely want to do this to the body) so that when a key is pressed the function is called.
Code:
document.getElementById("myID").onkeypress=function(e) {
    var e = window.event || e
    var keyunicode = e.charCode || e.keyCode

    var keyPressToPageMap = {
        37   :  'west',
        38   :  'north',
        39   :  'east',
        40   :  'south'
    };
    
    if(keyPressToPageMap[keyunicode]){
        window.location = keyPressToPageMap[keyunicode] + '.php';
    } 
}
 
Back
Top Bottom