Reputation: 11045
I am trying to click into a textarea using jquery and then press the spacebar. So far I've got the click aspect, easy enough: $( "textarea" ).click()
, but how can I now press spacebar?
Note: should be spacebar because of additional functionality linked to spacebar event press.
Upvotes: 0
Views: 3726
Reputation: 318312
The spacebar inserts a ..... wait for it ....... space, so why not just add a space to the value
$( "textarea" ).val(function(_, val) { return val + ' '; }).focus();
Also, clicking a textarea .... wait for it .... focuses the textarea, and there's an event for that.
There are also ways to trigger events manually, but you have to know what event to trigger
var e = $.Event("keyup", { which: 32 });
$("textarea").trigger( e );
Upvotes: 4
Reputation: 399
jQuery allows creation of an event, as shown in their documentation which you can then pass to the trigger function to fire it.
$("textarea").trigger($.Event("keydown", {
which: 32
}));
You may need to fire an appropriate keyup and/or keypress depending on the events being listened for by the handlers you want to trigger.
Upvotes: 1
Reputation: 11045
Got it, thanks for the input:
$( "textarea" ).trigger({type: 'keypress', which: 32, keyCode: 32});
$('textarea').focus()
Upvotes: 0