ganapati
ganapati

Reputation: 625

onkeypress() not working

i am trying to catch the keypress event on the window (html page opened with an app which uses gecko engine)

function onkeypress(){
      alert("key pressed !")
}

i expect this function to be called whenever any button is clicked, when the focus is on window. But the function is not been called. Any idea what is going wrong here? Thanks ...

Upvotes: 0

Views: 9137

Answers (2)

Nick Craver
Nick Craver

Reputation: 630389

You need to set it as the handler on the window object if that's what you're after, like this:

window.onkeypress = function() {
  alert("key pressed !")
};

This will capture all keypress events that bubble up (the default behavior, from wherever in the page it happened, with the exception of <iframe>, videos, flash, etc). You can read more about event bubbling here.

Upvotes: 4

Sarfraz
Sarfraz

Reputation: 382696

You should assign that function to an element:

var elem = document.getElementById('id-here');

elem.onkeypress = function(){
  alert("key pressed !");
};

Upvotes: 4

Related Questions