Make div element receive focus

JavascriptHtml

Javascript Problem Overview


How can I make an HTML <div> element receive focus, so elements will be put into focus when focus() is called on them?

Javascript Solutions


Solution 1 - Javascript

Set the tabindex="0" on the div, on the assumption that you want the divs 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChito AdinugrahaView Question on Stackoverflow
Solution 1 - JavascriptDavid ThomasView Answer on Stackoverflow