How to simulate a key press by pressing a different key - javascript

I want to hide the "suggested" options list that appears underneath the search input when you start typing something on the Wordpress search plugin, what I need specifically is to fire the "Escape" key event when I press down the "Delete" key, I tried the following jquery function but it doesn't work as I expected.
$('form.search-form').keydown(function (e) {
// keycode for Delete key
if (e.keyCode == 46) {
var a = $.Event("keydown");
// keycode for Esc key
a.which = 27;
a.keyCode = 27;
$(document).trigger(a);
}});
Any help? Thanks in advance

Updated (original question was unclear)
Live demo here (click).
When the delete key is pressed, change the keyCode to the esc key, then use trigger to simulate a press of esc.
$('input').keydown(function (e) {
// keycode for delete
if (e.keyCode == 46) {
console.log('delete key pressed.');
e.keyCode = 27;
$(this.target).trigger(e);
}
});
$('input').keydown(function (e) {
// keycode for esc
if (e.keyCode == 27) {
console.log('esc key pressed.');
}
});
Old answer (leaving this here because it is similar.)
Your question is an X/Y problem. You don't need to fire another keydown, event, you just need to repeat the same functionality, so extract the esc event's code into a function and reuse in the del key's event. Live demo here (click).
$('input').keydown(function (e) {
// keycode for delete
if (e.keyCode == 46) {
myFunction(e);
}
});
$('input').keydown(function (e) {
// keycode for esc
if (e.keyCode == 27) {
myFunction(e);
}
});
function myFunction() {
alert('Look, Ma! Code reuse!');
}
Better yet, do this! Live demo here (click).
$('input').keydown(function (e) {
// keycodes for delete and esc
if (e.keyCode == 46 || e.keyCode == 27) {
myFunction(e);
}
});
function myFunction() {
alert('Look, Ma! Code optimization!');
}

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

Triggering a specific keyPress

So I want to trigger a 'tab' event on a down keypress, and a 'shift+tab' event on a up keypress. Here's what I've got so far, but I can't seem to set the keyCode of the Keypress event. I read that keyCode was being deprecated, but I tried code also (which does set), but it doesn't trigger the action on input.
if (e.keyCode === 38) {
// trigger a shift tab
console.log('up key was pressed')
}
if (e.keyCode === 40) {
console.log('down key was pressed')
let event = new KeyboardEvent('keyPress', { keyCode: 9 })
window.dispatchEvent(event)
}
https://jsfiddle.net/0Lv9bthd/18/ to capture up and down arrow presses you need keydown, can't use keypress
window.addEventListener("keydown", function(e) {
console.log(e.keyCode);
if (e.keyCode == 38) {
console.log('up key was pressed');
}
});

If key pressed after an input clicked

I want to know if the user clicked the input and after that pressed the enter key:
$('#AdsData tr td input').live('keypress', function (e) {
// if the Enter key is presses
if (e.which == 13) {
}
});
I tried it: clicked an input and pressed enter but the function wasn't called..
may be you can try doing with e.which and e.keyCode both this way:
var kc = e.which || e.keyCode;
if (kc == 13) {
and instead of keypress try with keyup or keydown
Try this
$('input').keydown(function(event) {
if(event.which == 13) {
alert('Enter.');
}
});
if the input element is part of a form, pressing enter will most likely submit the form. in that case try this:
$("#your_form").on("submit", function() {});

keypress event is not fired when we press enter key

I am facing a problem regarding to the keypress event. When I press the enter key then keypress event is not fired but it is working fine with the other keys.
Here is my code :
$(document).ready(function () {
alert('hi');
$("#ctl00_popupPageBody_txtFirstName,#ctl00_popupPageBody_txtLastName").keypress(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
alert(code);
if (code == 13) { //Enter keycode
//Do something
}
});
});
You should use keyup event for this
$(document).ready(function() {
$("#ctl00_popupPageBody_txtFirstName,#ctl00_popupPageBody_txtLastName").keyup(function(e) {
if (e.which == 13) {
//Enter keycode //Do something
}
});
});
Use just e.which as its normalized across keys:
$(document).ready(function () {
alert('hi');
$("#ctl00_popupPageBody_txtFirstName,#ctl00_popupPageBody_txtLastName").keypress(function (e) {
var code = e.which;
alert(code);
if (code === 13) { //Enter keycode
e.preventDefault();
//your code goes here
}
});
});
Note: in my case I bind do .keydown

'Alt' keyup event don't work on Firefox

i try to capture this key : alt+arrow down, alt+arrow up.
First, i capture alt key down :
var isAlt = false;
$(document).keydown(function (e) {
if(e.which == 18){isAlt=true;}
}).keyup(function (e) {
if(e.which == 18){isAlt=false;}
});
this code is ok, and alt keyup is detected.
But, if i add arrow key down, when arrow keydown, it's ok, but after alt keyup is not detected :
var isAlt = false;
$(document).keydown(function (e) {
if(e.which == 18){isAlt=true;}else{
if(e.which == 38 && isAlt == true) {
//action code here work
console.log('action ok');
}
}
}).keyup(function (e) {
if(e.which == 18){isAlt=false;}
});
You can try this on console, and after log 'action ok', you need press again alt key for "isAlt = false".
But, this code work fine on Chrome.
Anyone have one idea for correct this bug ?
You need to check the event.altKey property: https://developer.mozilla.org/en/DOM/KeyboardEvent

Categories