Just wondering. Is it possible to invoke a key press event in JavaScript without ACTUALLY pressing the key ? For example lets say, I have a button on my webpage and when that button is clicked I want to invoke a event as if a particular key has been pressed. I know it weird but can this be done in JavaScript.
Invoking KeyPress Event Without Actually Pressing Key
Asked Answered
Yes, this can be done using initKeyEvent. It's a little verbose to use, though. If that bothers you, use jQuery, as shown in @WojtekT's answer.
Otherwise, in vanilla javascript, this is how it works:
// Create the event
var evt = document.createEvent( 'KeyboardEvent' );
// Init the options
evt.initKeyEvent(
"keypress", // the kind of event
true, // boolean "can it bubble?"
true, // boolean "can it be cancelled?"
null, // specifies the view context (usually window or null)
false, // boolean "Ctrl key?"
false, // boolean "Alt key?"
false, // Boolean "Shift key?"
false, // Boolean "Meta key?"
9, // the keyCode
0); // the charCode
// Dispatch the event on the element
el.dispatchEvent( evt );
what is the "el" (double code not included) in your code ? –
Leopard
In typescript I had to do:
const evt = new KeyboardEvent("keypress", { shiftKey: true, etc... });
–
Trypsin If you're using jquery:
var e = jQuery.Event("keydown");
e.which = 50; //key code
$("#some_element").trigger(e);
so for example if I have a button as
<input type='button' onclick='DisplayKeyCode()'>
, what needs to be included in the function DisplayKeyCode()
so as it alerts the key code (50 in this case) –
Bugbear Instead of using "onclick" use onkeydown="DisplayKeyCode(event)" and alert event.keyCode. –
Pernod
what is
event.keyCode
in this case ? I mean do I have to define keyCode
anywhere ? –
Bugbear No, it is an event object passed by the browser. "event.keyCode" is a code of a key that you pressed. –
Pernod
Sorry But it doesn't work. I tried this -
function DisplayCode(event){
var event = jQuery.Event("keydown");
event.which = 50;
alert(event.keyCode);
}
and html as <input type="text" onkeydown="DisplayCode(event);">
–
Bugbear let us continue this discussion in chat –
Pernod
© 2022 - 2024 — McMap. All rights reserved.