Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 294
Chito Adinugraha Avatar asked Apr 28 '13 09:04

Chito Adinugraha


People also ask

How can I make my div receive focus?

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.

What elements can receive focus?

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 .

How do you add focus to an element?

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.

How do I make a div not focusable?

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.


1 Answers

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

like image 138
David Thomas Avatar answered Oct 03 '22 09:10

David Thomas