Simulate Keypress With jQuery

JavascriptJqueryKeyboard

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Another option:

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

http://api.jquery.com/trigger/

Solution 3 - Javascript

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.

http://docs.jquery.com/Events/trigger#eventdata

Read the above documentation for more details.

Solution 4 - Javascript

You could try this SendKeys jQuery plugin:

http://bililite.com/blog/2011/01/23/improved-sendkeys/

> $(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).

Solution 5 - Javascript

This works:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDodinasView Question on Stackoverflow
Solution 1 - JavascriptAndrew CulverView Answer on Stackoverflow
Solution 2 - JavascriptDenis IvanovView Answer on Stackoverflow
Solution 3 - JavascriptDmitriy LikhtenView Answer on Stackoverflow
Solution 4 - JavascriptRobert HarveyView Answer on Stackoverflow
Solution 5 - JavascriptAnoop P SView Answer on Stackoverflow