Simulating a Keypress Event from Javascript Console

49,618

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

Share:
49,618
Philip Kirkbride
Author by

Philip Kirkbride

Updated on July 11, 2022

Comments

  • Philip Kirkbride
    Philip Kirkbride almost 2 years

    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
    Philip Kirkbride about 11 years
    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.
  • Benjamin Gruenbaum
    Benjamin Gruenbaum about 11 years
    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
  • Philip Kirkbride
    Philip Kirkbride about 11 years
    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?
  • Benjamin Gruenbaum
    Benjamin Gruenbaum about 11 years
    This triggers a general keypress, I can edit the answer to let you choose which key was being pressed if you'd like.
  • Philip Kirkbride
    Philip Kirkbride about 11 years
    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
    Philip Kirkbride about 11 years
    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. jsfiddle.net/taj8H/3
  • Benjamin Gruenbaum
    Benjamin Gruenbaum about 11 years
    @PhilipK this is because you are attaching an event to keyup and not keydown, see jsfiddle.net/EWqfJ (or you can change both to keyup)