Jump to content

Recommended Posts

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>

Link to comment
https://forums.phpfreaks.com/topic/246999-calling-a-function-with-keypress/
Share on other sites

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  :(

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: &#039;west&#039;, 38: &#039;north&#039;, 39: &#039;east&#039;, 40: &#039;south&#039; };<br />
	if (keys[key]) window.location.href = keys[key] + ".php";<br />
};<br />


This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.