views:

2250

answers:

3

Hello,

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?

Thanks!

+1  A: 

You could try this SendKeys jQuery plugin:

http://bililite.com/blog/2008/08/20/the-fnsendkeys-plugin/

Robert Harvey
+1  A: 

This might answer your question.

themis
+4  A: 

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.

Dmitriy Likhten