Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Any ideas on how to achieve this?

like image 652
Dodinas Avatar asked Sep 23 '09 20:09

Dodinas


People also ask

How does jQuery detect keyboard press?

jQuery | keypress() The keypress() method in jQuery triggers the keypress event whenever browser registers a keyboard input. So, Using keypress() method it can be detected if any key is pressed or not.

How do you press a key in JavaScript?

Use the dispatchEvent Method to Simulate Keypress in JavaScript. We can use the dispatchEvent method to trigger a specific event. Copy window. addEventListener('keydown', (e) => { console.


2 Answers

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.

like image 63
Andrew Culver Avatar answered Sep 20 '22 23:09

Andrew Culver


Another option:

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

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

like image 29
Denis Ivanov Avatar answered Sep 18 '22 23:09

Denis Ivanov