I am trying to trigger space key with keycode in JavaScript. I will be sending voice command with space and it should trigger a space event with a keycode.
This is what I have done so far
if(firstword =="space"){
const ev = {
type: 'space',
keyCode: 32
}
editor.triggerOnKeyDown(ev);
The code works perfectly if I use enter or other keycode but not working for space, any idea?
You can try like this:
const ev = new KeyboardEvent('keydown',{'keyCode':32,'which':32});
Reference: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent
Ty to create addEventListener for space
window.addEventListener('keypress', function (e) {
if (e.keyCode == 32) {
alert('Space pressed');
}
}, false);
Related
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 handleBackspace function that does something if backspace is being pressed.
I tried this:
const handleBackspace = (e) => {
if(e.keyCode === 8) {
console.log('1')
}
}
//
<input onKeyPress={handleBackspace}>
But that doesn't work. (I tried it with keyCode 13 [enter] and it worked. But keyCode 8 [backspace] doesn't work) Can someone show me a solution?
As can be read here, onKeyPress only receives charCode instead of keyCode.
This gives us three possible answers to this issue:
Either change the event to onKeyDown
Change the listener to check e.charCode
Use e.which, which will work for both onKeyPress and onKeyDown.
onKeyDown detects keyCode events.
Try changing it to onKeyDown event.
Sandbox: https://codesandbox.io/s/react-basic-class-component-kzv2k?file=/src/index.js
handleBackspace = e => {
if (e.keyCode === 8) {
console.log("1");
}
};
render() {
return <input onKeyDown={this.handleBackspace} />;
}
Is there a way using jQuery or vanilla JS that I can pass down 2 keystrokes?
Example: When I press the space key as an event listener, both the enter and shift key should get pressed and passed down together. I managed for the code to run, but for one single key stroke. Can someone shine some light on this?
$(document).keydown(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == 13) {
document.addEventListener('keydown', function(ev) {
console.log(ev.which);
});
var e = new KeyboardEvent('keydown', {
'keyCode': 190,
'which': 190
});
console.log(e);
document.dispatchEvent(e);
}
});
To add modifiers like shift, ctrl, or alt to a KeyPress event, you can pass those properties in the second constructor argument. See the documentation here.
// ex. Shift+Enter
var e = new KeyboardEvent("keydown", {
key: "Enter",
shiftKey: true,
});
I need to capture normal text with upper and lower case letters, but I also want to pick up the key codes for alt, ctrl, esc, etc. I have attempted to run the two jquery functions .keypress and .keydown, and only accept special keys from .keydown, but when they are together, they only give to result of one. I am using Chrome, but I also need support for as many other browsers as possible.
You can fetch the state of special keys using jQuery.Event which is the first argument of the callback from a listener:
http://jsbin.com/epuqig/2/embed?live
jQuery(function($) {
$('input').on('keydown', function(event) {
// event.shiftKey
// event.ctrlKey
// Also to fetch the keyCode use:
// event.which
if ( event.which == 8 && event.shiftKey ) {
// Backspace and shift key is pressed
}
});
});
You can go vanilla if you don't care about old browsers:
window.addEventListener('load', function() {
var inputs = document.querySelectorAll('input');
[].forEach.call(inputs, function(input) {
input.addEventListener('keydown', keydownHandler, false);
});
}, false);
function keydownHandler(event) {
if ( event.keyCode == 8 && event.shiftKey ) {
// Backspace and shift key is pressed!
}
}
As you can see this is almost the same code snippets but the second one want work in < IE9
$(document).ready(function () {
$(document).keydown(function (e) {
var code = e.keyCode;
if(e.altKey) // you can also use - e.ctrlKey , e.shiftKey
// alt key
}).keyup(function (e) {
var code = e.keyCode;
});
});
I need to know how to trigger an enter key on an input. That is, in response to some other event (not a keypress), I need to trigger a keypress of value 13.
(Clarification, I do not want to trigger some event when the enter key is pressed. If I didn't know how to do that, I could find that that's been asked and answered several times on SO. I want the reverse. I am trying to develop a workaround that requires I emulate an 'enter' keypress.)
You can do this -
var e = $.Event( "keypress", { which: 13 } );
$('#yourInput').trigger(e);
http://api.jquery.com/category/events/event-object/
http://api.jquery.com/trigger/
var e = $.Event( "keyup", { keyCode: 13 } );
$('#yourInput').trigger(e);
Worked for me, instead of 'which', I used 'keyCode'
Simulate enter keypress
var e = jQuery.Event("keypress");
e.which = 13
e.keyCode = 13
$('#email').focus();
$('#email').trigger(e);
capture enter keypress
$('#email').keypress(function (e) {
if (e.which == '13') {
alert('code');
}});