13

Note this question. I see that there are other approaches besides just triggering the tab keypress event, but I'd still like to know why triggering the tab key press event doesn't move focus to the next input field.

Code Pen

HTML

<textarea></textarea> <textarea></textarea> <textarea></textarea> 

JS

$('textarea').on('keydown', function(e) { if (e.metaKey && e.which === 40) { console.log('test'); $(this).trigger({ type: 'keypress', which: 9 }); } }); 

1 Answer 1

15

Because the tab event is a native browser event/action for changing focus. The .trigger() function only triggers the event handlers that are assigned to it. Note there is more information given from jQuery's site:

The .trigger() function cannot be used to mimic native browser events, such as clicking on a file input box or an anchor tag. This is because, there is no event handler attached using jQuery's event system that corresponds to these events.

There is a plug-in for this though called jquery-simulate to handle this. That being said the tab key changing focus is actually a default action in the web browser. Firing a browsers native event does not mean it will do it's default action, as the documentation for KeyboardEvents mentions:

Note that manually firing an event does not generate the default action associated with that event. For example, manually firing a key event does not cause that letter to appear in a focused text input. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself.

Sign up to request clarification or add additional context in comments.

3 Comments

So .trigger()ing the event isn't the same as... triggering the event manually? That's misleading. Or is there something I'm missing?
Any idea why this isn't working? The page you linked to says "...can programmatically create an event that behaves exactly as if someone has actually...". I did everything in this guide, but it doesn't seem to be working.
@AdamZerner That's actually a bit misleading, in the documentation for the KeyEvents. There is a note at the bottom of the page which mentions: "Note that manually firing an event does not generate the default action associated with that event. For example, manually firing a key event does not cause that letter to appear in a focused text input. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.