Well I searched on Google but still didn't found the answer I was looking for.
I want to check if the user pressed a key, something like this -
if(document.onkeyup) {
// Some Stuff here
}
I know I can do this, this way -
document.onkeyup = getKey;
But the function getKey cannot return values.
So how can I check if the user pressed a key?
EDIT : I need pure Javascript for this thing..
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);
One way you could do it is using variables
and then you could check that variable some were else...
for example
var keypressed = "";
document.onkeyup = function(e){
if (typeof event !== 'undefined') {
keypressed = event.keyCode;
}
else if (e) {
keypressed = e.which;
}
return false; // Prevents the default action
}
You really should not be doing this but if you really must:
var getKey = (function () {
var currentKey = null;
document.onkeyup = function (event) {
// determine the pressed key (across browsers)
// by inspecting appropriate properties of `event`
// and update currentKey; E.g:
currentkey = event.which ? event.which : window.event.keyCode;
}
return function () {
return currentkey;
}
})();
This will give you the last key user pressed.
If you need to get the currently pressed key (until released) then you need to attach keydown event to update currentKey variable and keyup event to set it to null.
You have to attach the event to the window global object and to set a function that listen to the event.
This sample show you how to track the keyup and keydown events.
window.addEventListener('keydown', onKeyDown, true);
window.addEventListener('keyup', onKeyUp, true);
function onKeyDown(evt) {
// key up event as been fired
console.log(evt.keyCode);
}
function onKeyUp(evt) {
// key up event as been fired
console.log(evt.keyCode);
}
See element.addEventListener on MDN for more details.
I would use jquery and do something like this:
// arrow keys click
$(document).keyup(function(e) {
// left arrow
if (e.keyCode == "37" ) {
// left stuff
// right arrow
} else if (e.keyCode == "39") {
// right stuff
// up arrow
} else if (e.keyCode == "38") {
// up stuff
// down arrow
} else if (e.keyCode == "40") {
// down stuff
}
});
etc, for the different key codes seen here http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
If you are attempting to run an event to test when a certain key is pressed, you can use this.
document.addEventListener('keydown', function(event) {
var key_code = event.keyCode;
if (key_code === 38) {
alert('test);
}
});
Related
I am new to JavaScript and learning event handlers. How to detect click + specific key pressed concurrently? For example click+D, using pure (vanilla) js.
Edit:
I tried this way but its not detecting the click event when key is pressed.
The console.log("key "+keyPressed) statement is also executed continuously while key is in pressed state.
keyPressed=false;
function keyDown(event) {
var x = event.key;
if (x == "a" || x == "A") {
keyPressed=true;
console.log("key "+keyPressed);
}
}
function keyUp(event){
keyPressed=false;
console.log("key "+keyPressed);
}
function clickHelper(event){
console.log("---");
if(keyPressed){
console.log("*****");
}
}
IIRC you cannot use one event to detect if the mouse is held down AND a button is clicked. However, you can set a property called mouseDown of the document and register an event listener for mouse state.
var mouseDown = 0;
document.body.onmousedown = function () {
++mouseDown;
};
document.body.onmouseup = function () {
--mouseDown;
};
document.body.onkeydown = function (e) {
if (mouseDown && e.key === 'd') {
alert('D was pressed while clicking');
}
};
I used some code from this stackoverflow post for this.
Possible Duplicate:
Which keycode for escape key with jQuery
How to detect escape key press in IE, Firefox and Chrome?
Below code works in IE and alerts 27, but in Firefox it alerts 0
$('body').keypress(function(e){
alert(e.which);
if(e.which == 27){
// Close my modal window
}
});
Note: keyCode is becoming deprecated, use key instead.
function keyPress (e) {
if(e.key === "Escape") {
// write your logic here.
}
}
Code Snippet:
var msg = document.getElementById('state-msg');
document.body.addEventListener('keypress', function(e) {
if (e.key == "Escape") {
msg.textContent += 'Escape pressed:'
}
});
Press ESC key <span id="state-msg"></span>
keyCode is becoming deprecated
It seems keydown and keyup work, even though keypress may not
$(document).keyup(function(e) {
if (e.key === "Escape") { // escape key maps to keycode `27`
// <DO YOUR WORK HERE>
}
});
Which keycode for escape key with jQuery
The keydown event will work fine for Escape and has the benefit of allowing you to use keyCode in all browsers. Also, you need to attach the listener to document rather than the body.
Update May 2016
keyCode is now in the process of being deprecated and most modern browsers offer the key property now, although you'll still need a fallback for decent browser support for now (at time of writing the current releases of Chrome and Safari don't support it).
Update September 2018
evt.key is now supported by all modern browsers.
document.onkeydown = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key === "Escape" || evt.key === "Esc");
} else {
isEscape = (evt.keyCode === 27);
}
if (isEscape) {
alert("Escape");
}
};
Click me then press the Escape key
Using JavaScript you can do check working jsfiddle
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
};
Using jQuery you can do check working jsfiddle
jQuery(document).on('keyup',function(evt) {
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
});
check for keyCode && which & keyup || keydown
$(document).keydown(function(e){
var code = e.keyCode || e.which;
alert(code);
});
Pure JS
you can attach a listener to keyUp event for the document.
Also, if you want to make sure, any other key is not pressed along with Esc key, you can use values of ctrlKey, altKey, and shifkey.
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
//if esc key was not pressed in combination with ctrl or alt or shift
const isNotCombinedKey = !(event.ctrlKey || event.altKey || event.shiftKey);
if (isNotCombinedKey) {
console.log('Escape key was pressed with out any group keys')
}
}
});
pure JS (no JQuery)
document.addEventListener('keydown', function(e) {
if(e.keyCode == 27){
//add your code here
}
});
Below is the code that not only disables the ESC key but also checks the condition where it is pressed and depending on the situation, it will do the action or not.
In this example,
e.preventDefault();
will disable the ESC key-press action.
You may do anything like to hide a div with this:
document.getElementById('myDivId').style.display = 'none';
Where the ESC key pressed is also taken into consideration:
(e.target.nodeName=='BODY')
You may remove this if condition part if you like to apply to this to all. Or you may target INPUT here to only apply this action when the cursor is in input box.
window.addEventListener('keydown', function(e){
if((e.key=='Escape'||e.key=='Esc'||e.keyCode==27) && (e.target.nodeName=='BODY')){
e.preventDefault();
return false;
}
}, true);
Best way is to make function for this
FUNCTION:
$.fn.escape = function (callback) {
return this.each(function () {
$(document).on("keydown", this, function (e) {
var keycode = ((typeof e.keyCode !='undefined' && e.keyCode) ? e.keyCode : e.which);
if (keycode === 27) {
callback.call(this, e);
};
});
});
};
EXAMPLE:
$("#my-div").escape(function () {
alert('Escape!');
})
On Firefox 78 use this ("keypress" doesn't work for Escape key):
function keyPress (e)(){
if (e.key == "Escape"){
//do something here
}
document.addEventListener("keyup", keyPress);
i think the simplest way is vanilla javascript:
document.onkeyup = function(event) {
if (event.keyCode === 27){
//do something here
}
}
Updated: Changed key => keyCode
I have a question. I have made a small site in HTML and vanilla JS to act as a counter. It is working fine, but I wanted to add a function that would allow the user to add or subtract 1 from the counter by pressing "+" or "-", in the numpad or not.
What is the easiest way to do this in vanilla JS?
Sure, just attach to the keyup events and increment or decrement the value when the proper key is pressed.
var value = 0;
document.addEventListener("DOMContentLoaded", function(event) {
document.querySelector(".valueHolder").innerHTML = value;
});
document.addEventListener("keyup", function(event) {
if (event.which == "187" || event.which == "107") { // + key
value++;
}
if (event.which == "189" || event.which == "109") { // - key
value--;
}
document.querySelector(".valueHolder").innerHTML = value;
console.log(event.which);
});
<div class="valueHolder"></div>
You will want to add an event listener on the document
document.addEventListener('keydown', myFunction);
function myFunction(e) {
var keyCode = e.keyCode();
...
}
You'll want to look up the keycodes for the keys you will be using (+ and -) and compare that value to keyCode. Then use a conditional to execute your adding or subtracting.
You would create an event handler, which would add or subtract from a global variable based on the key pressed, like this:
window.counter=0;
function key(ev){
if(ev.keycode==107) window.counter++;
if(ev.keycode==109) window.counter--;
}
document.onkeypress = key;
I'm trying to execute some code when multiple buttons are pushed, I'm trying this as an example but it's not working :
<script>
var map = {82: false, 84: false};
function keydown(e) {
if (e.keyCode in map) {
map[e.keyCode] = true;
if (map[82] && map[84]) {
alert(" all pressed ");
}
}
}
function keyup(e)
{
if (e.keyCode in map) {
map[e.keyCode] = false;
}
}
window.addEventListener('keyup', keyup);
window.addEventListener('keydown', keydown);
</script>
I get the alert even when only one button is pushed, ( i got it when both are pushed too )
What am i doing wrong please ?
You don't seem to be attaching your keyup handler, so once a key has been pressed it was forever marked as true in your map
window.addEventListener('keyup', keyup);
Try this:
var map = [];
onkeydown = onkeyup = function(e){
e = e || event; // to deal with IE
map[e.keyCode] = e.type == 'keydown';
if(map[82] && map[84]){
alert('all pressed');
}
}
This was also already answered here:
JavaScript multiple keys pressed at once
Please make sure you check to avoid posting a duplicate question.
I think I found the problem, the program doesn't execute the keyup fonction because of the alert, map[82] and map[84] are always true then.
I have a javascript window.open popup, and I want the popup to close itself when the user presses the ESC key. I can't figure out how to hook the keydown event (and on what object?) so that I can catch the ESC key.
I'm using jQuery.
Try something like this:
$(document).keydown(function(e) {
// ESCAPE key pressed
if (e.keyCode == 27) {
window.close();
}
});
It is possible to achieve with JS Without using jQuery.
window.onkeydown = function( event ) {
if ( event.keyCode == 27 ) {
console.log( 'escape pressed' );
}
};
event.key === "Escape"
No more arbitrary number codes!
document.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; in ES6+
if (key === "Escape") {
window.close();
}
});
Mozilla Docs
Supported Browsers
Remember that you must use the function #Gumbo posted in the popup-window... So you will need to include JQuery in the popup and execute the function there, not the window that opens the popup.
To handle both esc and enter key on dialog
window.onkeydown = function(event) {
if(event.keyCode===27|| event.keyCode===13){
window.close();
}
}
You can easily achieve bind key events using Jquery.
Here you can use .keydown()
List of keyboard keys codes
$(document).keydown(function(e) {
if (e.keyCode == 27) {
window.close();
}
});
#Gumbo 's answer is good but often you need to unhook this behaviour so I suggest to use the one event handler:
$(document).one('keydown', function(e) {
// ESCAPE key pressed
if (e.keyCode == 27) {
window.close();
}
});
OR
$(document).on('keydown', function(e) {
// ESCAPE key pressed
if (e.keyCode == 27) {
window.close();
}
});
and when ready to stop the behaviour
$(document).off('keydown');
In case if any looking for angularjs popup solution here you go
*this is without using ui-bootstrap dependency(only recommended when there is no other way)
$scope.openModal = function(index){
$scope.showpopup = true;
event.stopPropagation();//cool part
};
$scope.closeModal = function(){
$scope.cc.modal.showpopup = false;
};
window.onclick = function() {
if ($scope.showpopup) {
$scope.showpopup = false;
// You should let angular know about the update that you have made, so that it can refresh the UI
$scope.$apply();
}
};
//escape key functionality playing with scope variable
document.onkeydown = function (event) {
const key = event.key; // const {key} = event; in ES6+
if (key === "Escape") {
if ($scope.showpopup) {
$scope.showpopup = false;
// You should let angular know about the update that you have made, so that it can refresh the UI
$scope.$apply();
}
}
};
References: above answers and http://blog.nkn.io/post/hiding-menu-when-clicking-outside---angularjs/