How can I make an HTML <div>
element receive focus, so elements will be put into focus when focus()
is called on them?
You can make it focusable by adding a tabindex=0 attribute value to it. That will add the element to the list of elements that can be focused by pressing the Tab key, in the sequence of such elements as defined in the HTML document.
Understanding Focus The following elements can receive focus: <a> tags with an href attribute. Form controls and buttons (unless the element is disabled) Any element with a tabindex .
To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.
In order to make an prevent an element from taking focus ("non-focusable"), you need to use Javascript to watch for the focus and prevent the default interaction. In order to prevent an element from being tabbed to, use tabindex=-1 attribute. Adding tabindex=-1 will make any element focusable, even div elements.
Set the tabindex="0"
on the div
, on the assumption that you want the div
s to receive focus, rather than child elements.
Updated the answer to add a JS Fiddle demo, showing a JavaScript means of achieving this:
var divs = document.getElementsByTagName('div'); for (var i = 0, len = divs.length; i < len; i++){ divs[i].setAttribute('tabindex', '0'); }
JS Fiddle demo.
While composing the demo I found that tabindex="-1"
allows the element to receive mouse-clicks to assign focus, but not keyboard events (through the tab button), however (and as implied in the comment, earlier, by Fabricio Matté, a tabindex="0"
allows for both). So I've used that in the demo, and updated the original answer to reflect that change.
Behavior of tabindex="0"
versus tabindex="-1"
documented here: https://developer.mozilla.org/en-US/docs/Web/Accessibility/Keyboard-navigable_JavaScript_widgets#Using_tabindex
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With