Home > Back-end >  .focus() event behavior with Javascript
.focus() event behavior with Javascript

Time:03-19

I have these three tabs:

enter image description here

When a user uses the mouse and clicks on one of the tabs, (Compliance Notes in this example), the proper element on the tabbed page gets focus and is highlighted appropriately.

enter image description here

However, if the user uses the keyboard and presses the Tab key to highlight the tab they want, and then presses the Enter key to select that tab, the tabbed page gets focus. Then, via JavaScript, I set focus to the proper element on that tabbed page (by using the .focus() method on that element), and the same asp:DropDownList in the example behaves like the user not only selected the element, but clicked on it:

enter image description here

If you then either hit Enter or Tab, manually, the dropdown list closes and the element looks like it did if the user clicked on the tab versus using the keyboard:

enter image description here

So, is there a "simple" way, after I use the .focus() method, to then simulate either an Enter or Tab keystroke so the element will have focus but not have the dropdown list triggered? Or is there another way, using the .focus() method or some other approach, to prevent the dropdown list from being triggered when using the keyboard to navigate the page?

CodePudding user response:

The behavior you are mentioning seems to be related to the keydown event. Here's an example - when you type in the text field it should set focus on the dropdown. When you press enter in the text field, notice that the first example (using keydown) behaves similarly to what you reported. The second example (using keypress) does not.

document.querySelector('#typeHere').addEventListener("keydown", (e) => {
  document.querySelector('#focusMe').focus();
});

document.querySelector('#typeHere2').addEventListener("keypress", (e) => {
  document.querySelector('#focusMe2').focus();
});
<select id='focusMe'>
  <option>Test 1</option>
  <option>Test 2</option>
  <option>Test 3</option>
</select>

<input id='typeHere' >
<br><br>
<select id='focusMe2'>
  <option>Test 1</option>
  <option>Test 2</option>
  <option>Test 3</option>
</select>

<input id='typeHere2'>

  • Related