I want to move focus to next element (emulate tab key press)

Asked 2 years ago, Updated 2 years ago, 146 views

I would like to perform the same behavior (focus to the next element) as tab key press when certain events occur, such as pressing enter key.

For example, when I tried with the code below, the keyup (keyCode=9) event was triggered, but the focus did not move.Can I assume that manually triggering these key* events does not shift the focus?
What are the alternatives?

<!DOCTYPE html>
<html>
<body>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <script src="//code.jquery.com/jquery-3.2.1.min.js"></script>
    <script>
        $(document).on("keyup", "input", function(e){
            console.log(e.keyCode);
            if(e.keyCode==13){
                variable event=$.Event("keyup")
                event.keyCode=9;
                $(this).trigger(event);
                return false;
            }
        });
    </script>
</body>
</html>

javascript html jquery html5

2022-09-30 21:35

2 Answers

May I assume that manually triggering key* events like this will not shift the focus?

Yes, the standard states that throwing artificially created input events does not cause the browser to default behavior.

The only way to emulate is to re-implement the browser's algorithm for finding the following elements in JavaScript:There might already be a library like that.


2022-09-30 21:35

If you use jquery in the order of elements loaded into HTML, it will be quick.
I think it's just an array of selectable elements and focus on the elements.
However, for the focus position, save the selected position globally or
I think we have no choice but to determine the position from the current focus state.

var focusPos=0;
varsec = 0;
values = [ ];
$(document).ready(function(){
  sec = 0;
  elements=$('input[type="text"]:enabled');
  $('input[type="text"]:enabled')
  .focusin(function(e){
    for (no in elements) {
      if(e.target==elements[no]){
        focusPos = no;
        break;
      }
    }
  })
  .focusout(function(e){
    focusPos = 0;
  });
  setInterval(function(){
    sec++;
    if($("#nextFocus").attr("max")<=sec){
      sec = 0;
      focusPos++;
      if(elements.length<=focusPos) {focusPos=0;}
      elements [focusPos].focus();
    }
    $("#nextFocus").val(sec);
  },1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<progress id="nextFocus" max="5" value="0"></progress><br/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>


2022-09-30 21:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.