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?
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.
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.
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.
Another option:
$(el).trigger({type: 'keypress', which: 13, keyCode: 13});
http://api.jquery.com/trigger/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With