Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't simulating a tab keypress move focus to the next input field?

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
    });
  }
});
like image 981
Adam Zerner Avatar asked Sep 06 '15 22:09

Adam Zerner


People also ask

How do you move focus on next field when Enter is pressed in HTML?

FCS is a jQuery plugin that has the ability to automatically move focus on the next form field when Enter key is pressed. The main goal of the plugin is to set focus on the next input field by pressing Enter key. It also supports any type of form controls like textarea, button, select, and more.

How do you press Enter in Javascript?

To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.


1 Answers

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.

like image 164
Spencer Wieczorek Avatar answered Oct 14 '22 07:10

Spencer Wieczorek