Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register document.onkeypress event

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?

like image 750
Nilesh Pethani Avatar asked Aug 28 '12 05:08

Nilesh Pethani


People also ask

What is Onkeypress event?

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.

Which is type of key event * Onkeypress Onkeydown Onkeyup all of the above?

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 ).

What is the difference between Onkeyup and Onkeypress?

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.

What is the event for Onkeydown?

The onkeydown event occurs when the user is pressing a key (on the keyboard).


1 Answers

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

like image 188
Vishal Suthar Avatar answered Sep 19 '22 03:09

Vishal Suthar