Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating a Keypress Event from Javascript Console

I want to simulate a Keypress event using the Javascript Console. I see lots of answers using an input element. I don't want to use an input element. I just want to paste some code into the Javascript console and have a keypress event simulated(specifically the back space button).

Answers using jQuery are welcome.

like image 531
Philip Kirkbride Avatar asked Mar 30 '13 18:03

Philip Kirkbride


People also ask

Can you simulate a keypress in JavaScript?

We use event handlers to simulate keypress events in JavaScript. An event in JavaScript, as the name suggests, refers to actions taken by the browser or user.

Is it possible to simulate key press event programmatically?

The answer is: There is no way to programmatically trigger input keys in the sandboxed browser environment under normal circumstances.

How do you simulate keystrokes?

To simulate native-language keystrokes, you can also use the [Xnn] or [Dnn] constants in the string passed to the Keys method. nn specifies the virtual-key code of the key to be “pressed”. For instance, [X221]u[X221]e will “type” the u and e characters with the circumflex accent.

How do you get if a key is pressed in JavaScript?

JavaScript keyboard eventskeydown : Keydown happens when the key is pressed down, and auto repeats if the key is pressed down for long. keypress : This event is fired when an alphabetic, numeric, or punctuation key is pressed down. keyup : Keyup happens when the key is released.


1 Answers

jQuery has a .keypress method accepting no arguments that simulates a keypress.

$("#target").keypress();

Will trigger a keypress on #target

If you'd like to also select which key was pressed, you can use .trigger. This example is from the docs:

var e = $.Event("keydown", { keyCode: 8}); //"keydown" if that's what you're doing
$("body").trigger(e);

The key code 8 is the key code for backspace in JavaScript.

Let me know how that works for you :)

like image 152
Benjamin Gruenbaum Avatar answered Oct 03 '22 02:10

Benjamin Gruenbaum