1

I have created a portfolio site and whilst browsing the images, I want users to be able to navigate using the arrow keys. I have the following code which works fine in Firefox but not Chrome, Safari or IE.

$(document).keypress(function (evt) { if (evt.keyCode == 39) { evt.preventDefault(); $.scrollTo('+=564px', 800, { axis:'x' }); } else if (evt.keyCode == 37) { evt.preventDefault(); $.scrollTo('-=564px', 800, { axis:'x' }); } }); 

I have the scrollTo plugin installed and working as well as a valid jQuery file so it's not an issue with these. Can anyine tell me why this might not function in other browsers?

Live example here.

Help always appreciated!

2
  • Do you get the expected behavior in FF3 or 4? In FF3, it's definitely wonky. Commented Feb 22, 2011 at 16:40
  • I'm using FF 3.6 and it works fine to me. It has now been updated with the code suggested by @Neurofluxation below, see if that makes any difference. Commented Feb 22, 2011 at 16:47

2 Answers 2

6

Try this:

$(document).bind('keydown',function(evt) { }); 

instead of

$(document).keypress(function(evt) { }); 

This is because IE handles KeyPress differently to FireFox.

EDIT as you were so nice about getting a decent answer:

I would also change your statement to a switch:

$(document).bind('keydown',function(evt) { switch(evt.keyCode) { case 65: alert("you pressed key 65"); break; } }); 
Sign up to request clarification or add additional context in comments.

2 Comments

What a hero! Thanks for this, has made my day!
+1, keydown is definitely the correct event. You could use $(document).keydown(function(evt) {}); instead of bind().
3

If you want to make this cross-browser, you should also be aware the keyCodes may not be the same across browsers. jQuery offers the property event.which, which is supposed to normalize the differences between browers.

http://api.jquery.com/event.which

From the docs:

event.which normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.

4 Comments

+1 You were a little quicker. :o) Using event.which should properly solve the issue if OP does want the keypress event (which is not the same as keydown). Either way, event.which is the recommended property to use.
@Andrea, @patrick: keypress is the wrong event for handling non-printable keys such as arrow keys, which is what the OP was after.
I agree. This is why I wrote "You should also be aware..." :-)
@Andrea: The problem is not detecting which key was pressed, it's whether the event is fired at all. In some browsers, keypress is not fired for arrow keypresses. keydown always fires.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.