File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes HTML, CSS and JavaScript and the fly likes onKeyPress -> trapping keys Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "onKeyPress -> trapping keys" Watch "onKeyPress -> trapping keys" New topic

onKeyPress -> trapping keys

David Hall

Joined: Jul 16, 2001
Posts: 1
I'm trying to capture when the user presses the space bar. I have the basics of the code worked out (see below); however, I have a slight problem. There's a text box on this page and I do NOT want my event to fire if they are currently typing in the text box. Any ideas? Thanks so much for your help!
<script type="text/javascript" language="JavaScript">
function keypress(e) {

var tmp=0;

if (navigator.appName == "Microsoft Internet Explorer")
tmp = window.event.keyCode;
tmp = e.which;
// if space bar hit
if (tmp == 32) {
Tim McDonald

Joined: Jul 17, 2001
Posts: 1
I've just been investigating a simular 'key-press' for the enter key. Substitute the 'space' key and you should be in business.
Netscape browsers require you to "capture" the event before you can do anything with it where Internet Explorer does not. Also Netscape uses a little bit different way to pass the event to the function.
Here is some code that works in Netscape 4+, Netscape 6 and Internet Explorer 5 browsers. It detects When a key has been pressed and then displays the key and its ascii code. You will also notice that I place focus to the window after the alert, this is because Netscape 6 requires that so that you can detect the next key. Hope this helps and good luck.
Neil M

Joined: Jul 23, 2001
Posts: 9
Add an onFocus() and onBlur() to your text field:
onFocus="cursorInField(true)" onBlur="cursorInField(false)"
then the function:
function cursorInField(isIt) {
spaceBarCaptureDisabled = isIt;
then in your capture key function, check for that variable:
if (!spaceBarCaptureDisabled) {
// run space bar commands here

I agree. Here's the link:
subject: onKeyPress -> trapping keys
It's not a secret anymore!