How to Detect Keypresses in JavaScript

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 detect if a certain key is being pressed

using keyCode you can get the specific key. This example works if you press enter keyword (code 13). Check this out: https://keycode.info/

document.addEventListener("keypress", function(event) {  if (event.keyCode == 13) {   console.log('Hello world');  }});

Using Javascript, how can I detect a keypress event but NOT when the user is typing in a form field?

Sniffing on the event target property's tagName would perhaps be sufficient. The below obviously isn't exhaustive-- there's several edge cases to consider-- but it's a start. Try typing when in the form elements and then just when focused elsewhere in the document:

document.onkeyup = checkKey;
function checkKey(evt) {
const formElements = ['INPUT', 'TEXTAREA', 'SELECT', 'OPTION'];
evt = evt || window.event;
if (formElements.includes(evt.target.tagName)) {
console.log('ignore me!');
} else {
console.log('do something!');
}
}
<h1>my form</h1>
<form>
<label for="name">name</label>
<input id="name" name="name" />
<br/>
<label for="aboutme">about me</label>
<textarea id="aboutme" name="aboutme"></textarea>
<br/>
<label for="ghostbuster">ghostbuster</label>
<select id="ghostbuster" name="ghostbuster">
<option value="winstonzeddmore">Winston Zeddmore</option>
<option value="egonspangler">Egon Spangler</option>
<option value="petervenkman">Peter Venkman</option>
<option value="raystanz">Ray Stanz</option>
</select>
</form>

<p> some text</p>

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)" />

JavaScript - Detecting Key Presses

I am able to get at two keys to show at once with the code you provided. I have modified the example to display the data, and a graphical representation. If you are not seeing multiple keys work at once, it is probably a browser limitation.

I am using Chrome 53 on OSX

// get key presses
var keys = { up: false, down: false, left: false, right: false}
function keyUpdate(keyEvent, down) { // down is a boolean, whether the key event is keydown (true) or keyup (false) keyEvent.preventDefault(); // prevent screen from going crazy while i press keys. console.log(keyEvent.keyCode) switch (keyEvent.keyCode) {
case 87: // W key. case 38: // up key. keys.up = down; var key = document.querySelector('.up'); if (down){ key.classList.add('pressed'); } else { key.classList.remove('pressed'); } break; case 83: // S key case 40: // down key keys.down = down; var key = document.querySelector('.down'); if (down){ key.classList.add('pressed'); } else { key.classList.remove('pressed'); } break;
case 65: // A key case 37: // left arrow. keys.left = down; var key = document.querySelector('.left'); if (down){ key.classList.add('pressed'); } else { key.classList.remove('pressed'); } break; case 68: case 39: // right arrow. keys.right = down; var key = document.querySelector('.right'); if (down){ key.classList.add('pressed'); } else { key.classList.remove('pressed'); } break; default: if (down){ keys[keyEvent.keyCode] = down; } else if (keyEvent.keyCode in keys){ delete keys[keyEvent.keyCode]; } } var text = JSON.stringify(keys, null, 4); document.querySelector('.code').innerHTML = text;}
document.addEventListener("keydown", function(event) { keyUpdate(event, true);});
document.addEventListener("keyup", function(event) { keyUpdate(event, false);});

document.querySelector('.code').innerHTML = JSON.stringify(keys, null, 4);
h3 {  text-align: center;  font-family: sans-serif;  text-decoration: underline;  font-weight: normal;}.keys {  width: 150px;  margin: 0 auto;}.rows {  display: flex;  flex-direction: column;  justify-content: center;  align-items : center;}
.key{ flex: 1; width: 50px; max-width: 50px; height: 50px; background-color: #eee; text-align:center; line-height: 50px; border-radius: 3px; border: 1px solid #aaa; transition: all .2s ease; color : #555; font-size: 20px; font-weight: bold;}
.pressed{ color : #ddd; background-color: #aaa; border: 1px solid #eee;}
.columns{ display: flex; flex-direction: row; justify-content: space-arround;}
.code { background-color: #efefef; border: 1px solid #aaa;}
<h3> click here to start capturing keyboard input</h1><div class="keys rows">  <div class="key up">↑</div>  <div class="columns">    <div class="key left">←</div>        <div class="key down">↓</div>    <div class="key right">→</div>  </div></div><pre class="code"></pre>

How to detect if the pressed key will produce a character inside an input text-box?

This I think will do the job, or if not is very close and will need only minor tweaking. The thing you have to remember is that you can't reliably tell anything at all about any character that may be typed in a keydown or keyup event: that all has to be done in a keypress handler. The definitive resource for key events is http://unixpapa.com/js/key.html

You also need to consider pastes, which this code won't handle. You will need to have separate paste event handler (although this event isn't supported in Firefox < 3.0, Opera, and very old WebKit browsers). You'll need a timer in your paste handler since it's impossible in JavaScript to access the content that's about to be pasted.

function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}

<input type="text" onkeypress="alert(isCharacterKeyPress(event))">

Detect keypress event after enter has been hit

The simplest way to do it would be as follows

$('#searchbar').on('input keydown', function (e) {
if ($('#searchbar').val().length >= 3) {
$('.child-div').show();
}

if( e.which == 13){
$('.child-div').hide();
e.target.blur();
}
})

$('#searchbar').on('focus', function (e) {
if ($('#searchbar').val().length >= 3) {
$('.child-div').show();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type="text" class="form-control form-rounded rounded-pill" placeholder="Text input" id="searchbar">
<div class="child-div" style="background-color: blueviolet; width: 50%; height: 200px; display: none;">
CHILD DIV
</div>
</div>

How to detect keydown anywhere on page in a React app?

You can use useEffect hook to achieve this and adding an event listener to document:

import React, { useEffect } from "react";

export default ({ name }) => {
useEffect(() => {
function handleKeyDown(e) {
console.log(e.keyCode);
}

document.addEventListener('keydown', handleKeyDown);

// Don't forget to clean up
return function cleanup() {
document.removeEventListener('keydown', handleKeyDown);
}
}, []);

return <div>Keydown</div>;
};

Here is an example in action.

Assuming the <div> is focused via tabindex or similar, you'd be able to see see in the keydown handler that e.target would be the <div>. You can also wrap the functionality in another component and in it's keydown handler check if the keydown was executed on that element instead of outside using contains.

Here is another example that uses contains to check if the event target is within the div ref:

import React, { useEffect, useRef } from "react";

function Hello({ onKeyDown }) {
const ref = useRef();

useEffect(() => {
function handleKeyDown(e) {
// check if keydown was contained in target div
if (!ref.current || ref.current.contains(event.target)) {
return;
}

// Emit event to parent component
onKeyDown(e);
}

document.addEventListener("keydown", handleKeyDown);

return function cleanup() {
document.removeEventListener("keydown", handleKeyDown);
};
}, []);

return (
<div ref={ref} tabIndex="0">
foo bar baz
</div>
);
}

export default Hello;

Hopefully that helps!



Related Topics



Leave a reply



Submit