[javascript] 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?

This question is related to javascript jquery keyboard

The answer is


Another option:

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

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


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.


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


This works:

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to keyboard

How do I check if a Key is pressed on C++ Move a view up only when the keyboard covers an input field Move textfield when keyboard appears swift Xcode iOS 8 Keyboard types not supported Xcode 6: Keyboard does not show up in simulator How to dismiss keyboard iOS programmatically when pressing return Detect key input in Python Getting Keyboard Input Press Keyboard keys using a batch file Keylistener in Javascript