I want to register keypress events for a document using javascript.
I have used:
document.attachEvent("onkeydown", my_onkeydown_handler);
It works fine with IE, but not with Firefox and Chrome.
I also tried:
document.addEventListener("onkeydown", my_onkeydown_handler, true); // (with false value also)
But it still doesn't work with Firefox and Chrome.
Is there a solution, am I missing something?
The onkeypress event occurs when the user presses a key (on the keyboard). Tip: The order of events related to the onkeypress event: onkeydown. onkeypress. onkeyup.
The onKeyDown event is triggered when the user presses a key. The onKeyUp event is triggered when the user releases a key. The onKeyPress event is triggered when the user presses & releases a key ( onKeyDown followed by onKeyUp ).
The difference between onkeyup and onkeypressonkeypress is fired when a key on your keyboard is pressed. onkeyup is fired when you release the key on your keyboard. If you press any key and do not release it. onkeypress works for letters, numbers, and symbols without meta keys on your keyboard.
The onkeydown event occurs when the user is pressing a key (on the keyboard).
You are looking for:
EDIT:
Javascript:
document.addEventListener("keydown", keyDownTextField, false); function keyDownTextField(e) { var keyCode = e.keyCode; if(keyCode==13) { alert("You hit the enter key."); } else { alert("Oh no you didn't."); } }
DEMO: JSFIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With