Make div element receive focus
How can I make an HTML <div>
element receive focus, so elements will be put into focus when focus()
is called on them?
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