Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
212 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...