0

I would like to change the focus in the DOM based on the browser's own calculations of which element is the next focusable element.

I understand that...

  • Keypresses can't be triggered in most browsers by JavaScript (see https://stackoverflow.com/a/32429197/1766230), so we can't trigger the Tab key to go to the next focused element (nor would we want to since the keypress event could be overridden).
  • We could write some code to find all links/inputs/etc., find which one is currently focused, and trigger a focus on the next one. ... but that seems like it is just duplicating logic that is natively in the browser somewhere.

My question is: Can we utilize the browser's own logic for determining the next focusable element, and focusing on it?

Luke
  • 18,811
  • 16
  • 99
  • 115

1 Answers1

-2

No JS required for this.

Have you tried attribute tabindex ?

    <input type"text" tabindex="1">
    <input type"text" tabindex="3">
    <input type"text" tabindex="2">
    <input type"text" tabindex="5">
    <input type"text" tabindex="4">
    <input type"text" tabindex="7">
    <input type"text" tabindex="8">
    <input type"text" tabindex="6">

Referring to my source, you can use it for <a>, <textarea>, <select>, and <button> elements too.

Please let me know if this answer does not satisfy your question/needs.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
schogges
  • 351
  • 5
  • 12
  • This does not answer the question. I want to be able to *run JavaScript* that will change focus between these elements. – Luke Mar 01 '19 at 16:34
  • What about [https://stackoverflow.com/questions/7208161/focus-next-element-in-tab-index](https://stackoverflow.com/questions/7208161/focus-next-element-in-tab-index) ? Especially `onfocusout` Event could be useful. You can `.focus()` any focusable element after another element lost its focus. – schogges Mar 01 '19 at 16:47
  • Another problem with just writing some javascript to replicate the logic that already exists in the browser (such as in the answer you linked), is that there some browser and OS settings that change how _Tab_ works. For instance, on Macs there is a "Full keyboard access" system preference that effects how Firefox cycles between elements, and in Safari there is a browser preference that does the same. I would like to be able to call a method that handles all those considerations just like the browser does. – Luke Mar 04 '19 at 16:12