9

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.

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
  • 1
    Duplicate of [Simulate JavaScript Key Events](http://stackoverflow.com/questions/596481/simulate-javascript-key-events), because triggering the keypress from the browser console or from JavaScript code in a page are equivalent (and forbidden due to security reasons; see the answer on the original question). – Dan Dascalescu Sep 02 '15 at 05:59

1 Answers1

21

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 :)

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Can you format it so that nothing has to be clicked? I want an easy way to check if different devices have it enabled by pasting the code into console while device is in debug mode. – Philip Kirkbride Mar 30 '13 at 18:45
  • Nothing has to be clicked in this answer. You can just put $("#target").keypress(); in your console (presumably, in the end of your pasted code) and it'll trigger a keypress event – Benjamin Gruenbaum Mar 30 '13 at 18:46
  • I don't understand what key is being pressed int he example? Don't you need to pass through a number for the specific key? – Philip Kirkbride Mar 30 '13 at 18:48
  • This triggers a general keypress, I can edit the answer to let you choose which key was being pressed if you'd like. – Benjamin Gruenbaum Mar 30 '13 at 18:49
  • Yes thanks could you edit it to specifically simulate the backbutton being pressed? So I could paste it into the console and simulate someone having hit back space? I know the keycode is 8 – Philip Kirkbride Mar 30 '13 at 18:50
  • Thanks again I've made a fiddle which I hoped would alert "8" when your code ran. Could you edit it and add to the answer. http://jsfiddle.net/taj8H/3/ – Philip Kirkbride Mar 30 '13 at 19:01
  • @PhilipK this is because you are attaching an event to keyup and not keydown, see http://jsfiddle.net/EWqfJ/ (or you can change both to keyup) – Benjamin Gruenbaum Mar 30 '13 at 19:02