Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keypress event not working in IE and Chrome but working in FF

Any idea why this might happen? I would usually think that Chrome would be more forgiving with the codes?

$(document).keypress(function(e) {
    if(e.keyCode == 39) rightImage();
    if(e.keyCode == 37) leftImage();
});

Thats what my keypress key looks like. Am I missing something? rightImage(); and leftImage(); are functions which should be working becase I'm using those functions somewhere else too

Thanks for the help!

like image 850
hellomello Avatar asked Jun 10 '11 19:06

hellomello


People also ask

Which key was pressed for an keypress event in Internet Explorer?

System: ESC, SPACEBAR, ENTER.

Are keypress events deprecated?

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.

What is the difference between Keydown and keypress events?

The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.


2 Answers

Change keypress to keydown:

$(document).keydown(function(e) {
    if(e.keyCode == 39) rightImage();
    if(e.keyCode == 37) leftImage();
});

The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released.

In order to understand the difference between keydown and keypress, it is useful to understand the difference between a "character" and a "key". A "key" is a physical button on the computer's keyboard while a "character" is a symbol typed by pressing a button. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.

like image 169
jao Avatar answered Sep 18 '22 01:09

jao


Found the answer here: http://api.jquery.com/keypress/

"If you want to use arrows, delete, backspace keys in Chrome you must use keydown. keypress on these keys work only in Firefox and Opera."

Your code didn't work for me in iE8 (worked in FF), so I switched keypress to keydown. Works in IE now. Don't have Chrome here to test.

like image 38
AR. Avatar answered Sep 20 '22 01:09

AR.