2

I have to call a method when "enter" key is pressed anywhere in page but i don't want register any method call in each text box. I know it can be done by jQuery like this

$(document).keypress(function(e) {
  if(e.which == 13) {
    // enter pressed
  }
});

Kindly tell me how can I write same version of this code in plain javascript? Thanks in advance

rishi
  • 1,792
  • 5
  • 31
  • 63
  • possible duplicate of [Simplest way to detect keypresses in javascript](http://stackoverflow.com/questions/16089421/simplest-way-to-detect-keypresses-in-javascript) – Andy Aug 19 '15 at 10:47
  • Why don't you want jQuery? It is the same thing with a simpler API. – BAR Aug 19 '15 at 10:50

2 Answers2

3

Please try this

document.onkeypress = function (e) {
    if (e.keyCode == 13) {
        alert('cilcked')
    }
}

DEMO

Rino Raj
  • 6,264
  • 2
  • 27
  • 42
3
document.addEventListener("keydown", yourKeyDownFunction, false);

http://jsfiddle.net/9ZDxw/1/

Tom Doodler
  • 1,471
  • 2
  • 15
  • 41