Add event listener listening on keydown - javascript

I want to run a method whenever the ESC button gets clicked. In the onkeypress Event documentation I read that i will have to use keydown
Note: The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers. To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.
I managed to write a working example:
document.onkeydown = function (e) {
if (document.getElementById("fullscreen") !== null) {
var key = e.which || e.keyCode;
if (key === 27) {
alert(1);
}
}
}
<div id="fullscreen">test</div>
The event listeners in our project have a different pattern, so I tried rewrite it in the same pattern but the code isn't reacting on the key press.
document.getElementById("fullscreen").addEventListener("keydown",
function (e) {
var key = e.which || e.keyCode;
if (key === 27) {
alert(1);
}
});
<div id="fullscreen">test</div>
Why isn't the second code snippet reacting on the key press like the first snippet?

Related

Escape key pressing not run keydown event [duplicate]

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

Is there an alternative to deprecated e.which in JavaScript?

Im new to JavaScript event handling, I would like to trigger an event upon mousemove and left-click on a div element. My current implementation is to check that e.which == 1 when I trigger the mousemove event function. However, I have read that the e.which property is now deprecated (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which). My code:
div.addEventListener("mousemove", myEventFunction)
function myEventFunction(e){
if (e.which == 1){
//do something
}
}
Is there any alternative to perform this operation?
You can use event.button if it is gonna be a mouse event.
The MouseEvent.button read-only property indicates which button was pressed on the mouse to trigger the event.
function myEventFunction(e) {
e = e || window.event;
if ("buttons" in e) {
return button;
}
var button = e.which || e.button;
return button;
}
The above function returns the button value.

How to detect esc key press while showing jquery notification

I want to detect the key event of escape while displaying the jquery notification. But as this is blocking the input I'm unable to detecting key board event while noty is showing.
$(document).keyup(function(e) {
if (e.keyCode == 27) {
//your codes
}
});
Use This Code It Works Everywhere:
// define a handler
function doc_keyUp(e) {
if (e.keyCode == 27) {//27 is Esc KeyCode
alert('Escape Key Has Been Pressed!');
}
}
// register the handler
document.addEventListener('keyup', doc_keyUp, false);
You can use onkeyup to pass event handler like-
<input type="text" onkeyup="YourKeyupHandler(event)">
Now you can implement function like-
function YourKeyupHandler(event) {
event = event || window.event || event.srcElement;
if (event.keyCode == 27) {
//here you can do whatever you want
}
}

How can I check that a key has been pressed?

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);
}
});

What Javascript event is fired when "return" is clicked on an iPad when an input is selected?

Which Javascript event is fired when someone presses the "return" key on an iPad in Safari while an input is selected.
I'm using an input element, but not surrounding it in <form> tags. I submit the $('#input').value() when $('#button').click() occurs. However, I'd like to also like to be able to submit when someone presses "return" on the iPad keyboard.
I was overzealous, here is the answer:
jQuery Event Keypress: Which key was pressed?
You can detect the enter key event in safari on ipad with following way :
<body onkeyup="yourFunction(event)">
then in javaScript
function yourFunction(event) {
var e;
if(event) {
e = event;
} else {
e = window.event;
}
if(e.which){
var keycode = e.which;
} else {
var keycode = e.keyCode;
}
if(keycode == 13) {
alert("do your stuff");
}
};
What about using a <form> tag and binding your handler to the submit tag.
$("#myForm").submit(function (event) {
doStuff();
});
It's cleaner and simpler.

Categories