I want to pass a keydown event to another element. Along the way I found that :
$('input').keydown(function(e) {
$('textarea').keydown()[0].focus();
});
works and that:
$('input').keydown(function(e) {
setTimeout(function() { $('textarea').keydown()[0].focus(); }, 0);
});
doesn’t work. At least in Chrome.
Anyway I want to do this with the second method as I want it to first be able to do a ctrl+c or ctrl+x on an input that has text selected and then jump to the textarea.
Here’s a DEMO to see what I mean.
Why doesn’t the second way work? Also is there any way to accomplish this?
Works as expected. First of all, half of your code is irrelevant. :p
is equivalent to
and it transfers the focus to the
textareabefore the keyhandler resolves. The key ends up in thetextarea. and theinputdoesn’t even see it. (assume the code saysinputand notinout).The second example:
is equivalent to:
so, because of the timeout, first the
keydownevent completes, the key is accepted as input to theinput, and then the delayed function gets invoked and changes focus. Nothing further happens.I don’t know how to “repeat” or “rethrow” a keyboard event, in case you want to get the same keypress in both
inputandtextarea(if that’s what you wanted; I am not 100% sure what you wanted).EDIT: Okay: if it’s just Ctrl/Shift/another modifier key, return true so the default handler picks it up. If it’s Ctrl-C (i.e.
Ckey withctrlKeyset (metaKeyon Mac), do the timeout thing (so theinputcatches it before thefocus); if not, move focus immediately (so thetextareacatches it). Not trivial, and I can’t think of a better method at the moment.