Simulate Keypress With jQuery

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) { 
    //... Some type of code here to initiate "spacebar" //

Any ideas on how to achieve this?



The keypress event from jQuery is meant to do this sort of work. You can trigger the event by passing a string "keypress" to .trigger(). However to be more specific you can actually pass a jQuery.Event object (specify the type as "keypress") as well and provide any properties you want such as the keycode being the spacebar.

Read the above documentation for more details.


I believe this is what you're looking for:

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

From here.


Another option:

$(el).trigger({type: 'keypress', which: 13, keyCode: 13});


You could try this SendKeys jQuery plugin:

$(element).sendkeys(string) inserts string at the insertion point in an input, textarea or other element with contenteditable=true. If the insertion point is not currently in the element, it remembers where the insertion point was when sendkeys was last called (if the insertion point was never in the element, it appends to the end).


This works:

var event = jQuery.Event('keypress');
event.which = 13; 
event.keyCode = 13; //keycode to trigger this for simulating enter


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.