keydown, keyup, keypress not fired on non-input elements
If you want to capture one of the above events in javascript, in most cases, it will be on an input element (eg. a text box). But what if you want to capture a keypress anywhere on a document (eg. to delete a highlighted element from the page when the delete key is pressed, which is what I was trying to do)? I tried adding onkeydown to the body tag, but it would only fire in IE. Firefox, Safari, Chrome, and Opera all failed to fire the event unless I first clicked on a text box. But there is a way to do it...
After a little experimentation, I found that if a text box on the page received the focus, the event would fire even after that text box lost the focus. So I simply added a little more script to the body tag's onload event to set the focus on a text box and then blur again:
var txtbox = document.getElementById('my_text_box_id');if (txtbox.focus){txtbox.focus();if (txtbox.blur){txtbox.blur();}}
Hey presto, all browsers now fire the keydown event as soon as the page is loaded.
If you don't have a spare textbox handy on your page, you could always add one, and absolutely position it negatively so that it is not visible but can still receive the focus.