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.

1
  • 1
    Duplicate of 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). Commented Sep 2, 2015 at 5:59

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

7 Comments

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.
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
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?
This triggers a general keypress, I can edit the answer to let you choose which key was being pressed if you'd like.
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
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.