Netshine Software Limited







Home arrow Developer Blog Make Text BiggerMake Text SmallerReset Text Size

Jun 04
2009

keydown, keyup, keypress not fired on non-input elements

Posted by netshine in onkeyuponkeypressonkeydownkeyupkeypresskeydownJavascripthtmlformsfocusfiredeventcross browsercapture

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.



Comments (1)Add Comment
thanks
written by zrek, February 28, 2010
Thanks for the trick; also working with style visibility:hidden.
report abuse
vote down
vote up
Votes: +0

Write comment
quote
bold
italicize
underline
strike
url
image
quote
quote
smile
wink
laugh
grin
angry
sad
shocked
cool
tongue
kiss
cry
smaller | bigger

security code
Write the displayed characters


busy
Joomla! Tutorial
Take a look at our free tutorial for Joomla! Administrator...


Login Form





Lost Password?

© 2004-2010 Netshine Software Limited   Terms and Conditions