How to Check If the User Is Pressing a Key

Check if a key is down?

Is there a way to detect if a key is currently down in JavaScript?

Nope. The only possibility is monitoring each keyup and keydown and remembering.

after some period of time the key begins to repeat, firing off keydown and keyup events like a fiend.

It shouldn't. You'll definitely get keypress repeating, and in many browsers you'll also get repeated keydown, but if keyup repeats, it's a bug.

Unfortunately it is not a completely unheard-of bug: on Linux, Chromium, and Firefox (when it is being run under GTK+, which it is in popular distros such as Ubuntu) both generate repeating keyup-keypress-keydown sequences for held keys, which are impossible to distinguish from someone hammering the key really fast.

How do I check if the user is pressing a key?

In java you don't check if a key is pressed, instead you listen to KeyEvents.
The right way to achieve your goal is to register a KeyEventDispatcher, and implement it to maintain the state of the desired key:

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

public class IsKeyPressed {
private static volatile boolean wPressed = false;
public static boolean isWPressed() {
synchronized (IsKeyPressed.class) {
return wPressed;
}
}

public static void main(String[] args) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

@Override
public boolean dispatchKeyEvent(KeyEvent ke) {
synchronized (IsKeyPressed.class) {
switch (ke.getID()) {
case KeyEvent.KEY_PRESSED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = true;
}
break;

case KeyEvent.KEY_RELEASED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = false;
}
break;
}
return false;
}
}
});
}
}

Then you can always use:

if (IsKeyPressed.isWPressed()) {
// do your thing.
}

You can, of course, use same method to implement isPressing("<some key>") with a map of keys and their state wrapped inside IsKeyPressed.

How can I check that a key has been pressed?

You can do this in pure Javascript using the event object, without the need of external libraries such as jQuery.

To capture the keycode, just pass the event as parameter of getKey function:

function getKey(e)
{
window.alert("The key code is: " + e.keyCode);
}

document.onkeyup = getKey;

Frequently used keyCode list:

For a usefull list of keyCodes, you can check out this URL:

http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Setting the keyCode to a global variable:

If you are interested in capturing the keyCode for later usage, you can do something like this:

var keycode = "";

(...)

function getKey(e)
{
keycode = e.keyCode;
}

document.onkeyup = getKey;

window.alert("The key code is: " + keycode);

Setting the keyCode to the event source object:

If you don't like global variables, like me, you could also do something like this:

function getKey(e)
{
keycode = e.keyCode;

var objectFromEvent = e.currentTarget ? e.currentTarget : event.srcElement;

objectFromEvent.customProperty = keycode;
}

document.customProperty = "";
document.onkeyup = getKey;

// now the value is in the "customProperty" of your object =)

window.alert("The key code is: " + document.customProperty);

In java how do I check if a user is pressing a certain key?

You can use the KeyEvent to get the key code, and then check it.

E.g:

someCompunent.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_MINUS) {
// do the stuff
}
}
});

How do I detect keypresses in Javascript?

With plain Javascript, the simplest is:

document.onkeypress = function (e) {
e = e || window.event;
// use e.keyCode
};

But with this, you can only bind one handler for the event.

In addition, you could use the following to be able to potentially bind multiple handlers to the same event:

addEvent(document, "keypress", function (e) {
e = e || window.event;
// use e.keyCode
});

function addEvent(element, eventName, callback) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + eventName, callback);
} else {
element["on" + eventName] = callback;
}
}

In either case, keyCode isn't consistent across browsers, so there's more to check for and figure out. Notice the e = e || window.event - that's a normal problem with Internet Explorer, putting the event in window.event instead of passing it to the callback.

References:

  • https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keypress
  • https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener

With jQuery:

$(document).on("keypress", function (e) {
// use e.which
});

Reference:

  • http://api.jquery.com/on/

Other than jQuery being a "large" library, jQuery really helps with inconsistencies between browsers, especially with window events...and that can't be denied. Hopefully it's obvious that the jQuery code I provided for your example is much more elegant and shorter, yet accomplishes what you want in a consistent way. You should be able to trust that e (the event) and e.which (the key code, for knowing which key was pressed) are accurate. In plain Javascript, it's a little harder to know unless you do everything that the jQuery library internally does.

Note there is a keydown event, that is different than keypress. You can learn more about them here: onKeyPress Vs. onKeyUp and onKeyDown

As for suggesting what to use, I would definitely suggest using jQuery if you're up for learning the framework. At the same time, I would say that you should learn Javascript's syntax, methods, features, and how to interact with the DOM. Once you understand how it works and what's happening, you should be more comfortable working with jQuery. To me, jQuery makes things more consistent and is more concise. In the end, it's Javascript, and wraps the language.

Another example of jQuery being very useful is with AJAX. Browsers are inconsistent with how AJAX requests are handled, so jQuery abstracts that so you don't have to worry.

Here's something that might help decide:

  • http://www.jscripters.com/jquery-disadvantages-and-advantages/

How to find out what character key is pressed?

"Clear" JavaScript:

function myKeyPress(e){
var keynum;

if(window.event) { // IE
keynum = e.keyCode;
} else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}

alert(String.fromCharCode(keynum));
}
<input type="text" onkeypress="return myKeyPress(event)" />


Related Topics



Leave a reply



Submit