qwertymk
qwertymk

Reputation: 35276

passing a keydown to another element

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?

Upvotes: 4

Views: 2787

Answers (2)

Amadan
Amadan

Reputation: 198324

Works as expected. First of all, half of your code is irrelevant. :p

$('inout').keydown(function(e) {
  $('textarea').keydown()[0].focus();
});

is equivalent to

$('inout').keydown(function(e) {
  $('textarea').keydown(); // doesn't do anything sensible
  $('textarea')[0].focus();
});

and it transfers the focus to the textarea before the keyhandler resolves. The key ends up in the textarea. and the input doesn't even see it. (assume the code says input and not inout).

The second example:

$('input').keydown(function(e) {
  setTimeout(function() { $('textarea').keydown()[0].focus(); }, 0);
});​

is equivalent to:

$('input').keydown(function(e) {
  setTimeout(function() {
    $('textarea').keydown(); // doesn't do anything sensible
    $('textarea')[0].focus();
  }, 0);
});​

so, because of the timeout, first the keydown event completes, the key is accepted as input to the input, 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 input and textarea (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. C key with ctrlKey set (metaKey on Mac), do the timeout thing (so the input catches it before the focus); if not, move focus immediately (so the textarea catches it). Not trivial, and I can't think of a better method at the moment.

Upvotes: 2

gdoron
gdoron

Reputation: 150253

Pass enough time for the setTimeout delay

$('input').keydown(function(e) {
    setTimeout(function() { $('textarea').keydown()[0].focus(); }, 700); // 0.7 seconds
});

the keydown event on the textarea has no sense, and can be removed;

$('input').keydown(function(e) {
    setTimeout(function() { $('textarea').focus(); }, 700); // 0.7 seconds
});

Upvotes: 0

Related Questions