Simulate Keypress With jQuery

Dodinas picture Dodinas · Sep 23, 2009 · Viewed 150.3k times · Source

Using jQuery, how can I simulate (trigger?) a KeyPress when a link is clicked? For example, when a user clicks the following link:

<a id="clickforspace" href="#">Click Here</a>

Then, by clicking the link, it would be as if they pressed the "spacebar" on their keyboard.

Something like this, I'm assuming:

$("#clickforspace").click(function(e) { 
    e.preventDefault(); 
    //... Some type of code here to initiate "spacebar" //
                                      });

Any ideas on how to achieve this?

Answer

Andrew Culver picture Andrew Culver · Apr 12, 2012

I believe this is what you're looking for:

var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 40;
$("whatever").trigger(press);

From here.