cloudll Posted September 12, 2011 Share Posted September 12, 2011 Hi guys. Im very new to js, and im trying to use a little bit of it to improve a php/mysql game I have made. I have this code given to me, but it does nothing when I press the key associated with it. Could someone tell me what im doing wrong please. Thank you for any help. <script> function pageRedirector(keycode){ var keyPressToPageMap = { 37 : 'west', 38 : 'north', 39 : 'east', 40 : 'south' }; if(keyPressToPageMap[keycode]){ window.location = keyPressToPageMap[keycode] + '.php'; }; }; </script> Quote Link to comment https://forums.phpfreaks.com/topic/246999-calling-a-function-with-keypress/ Share on other sites More sharing options...
requinix Posted September 12, 2011 Share Posted September 12, 2011 And how is your pageRedirector function being called? Quote Link to comment https://forums.phpfreaks.com/topic/246999-calling-a-function-with-keypress/#findComment-1268505 Share on other sites More sharing options...
cloudll Posted September 12, 2011 Author Share Posted September 12, 2011 Erm, sorry, i have no idea. Is the function not supposed to be called from a key press? Sorry this is the first time I have attempted javascript. At the moment I have a compass image on my game screen, and when you click north, it loads the north.php file which updates the position of my character in my database. I wanted to use the keypress to improve it a little but im starting to think its a little over my head now Quote Link to comment https://forums.phpfreaks.com/topic/246999-calling-a-function-with-keypress/#findComment-1268507 Share on other sites More sharing options...
requinix Posted September 12, 2011 Share Posted September 12, 2011 Is the function not supposed to be called from a key press? You know that, but you haven't told JavaScript that. It won't fire the function unless you say "on this element's keypress event, execute this function". And actually you want keydown, not keypress. ... ... <br /> document.onkeydown = function(e) {<br /> e = e || window.event;<br /> key = e.keyCode || e.charCode;<br /> <br /> var keys = { 37: 'west', 38: 'north', 39: 'east', 40: 'south' };<br /> if (keys[key]) window.location.href = keys[key] + ".php";<br /> };<br /> Quote Link to comment https://forums.phpfreaks.com/topic/246999-calling-a-function-with-keypress/#findComment-1268530 Share on other sites More sharing options...
cloudll Posted September 12, 2011 Author Share Posted September 12, 2011 Thanks your awesome Quote Link to comment https://forums.phpfreaks.com/topic/246999-calling-a-function-with-keypress/#findComment-1268545 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.