Focusing a DIV in JavaScript

It is possible to focus a DIV or another HTML elements with JavaScript by using the tabindex tag, this tag allows us to stablish whether an element can be focused or not, with “-1” value elements can’t be tabbed but it can be focused, with “0” value the element can be focused via the keyboard and tabbed following the normal flow of the document. Values greater than 0 set the priority level for this tab flow, 1 is the most important value.

JavaScript:

<button id="button" onclick="clickSample();">Click Me!</button>
<div id="sampleDiv" tabindex="0"></div>

HTML:

document.getElementById('button').focus();
 
function clickSample(){
	console.log('click');
	document.getElementById('sampleDiv').focus();
	console.log(document.activeElement.tagName)
}

Sources:
http://snook.ca/archives/accessibility_and_usability/elements_focusable_with_tabindex
http://www.sitepoint.com/article/accessible-javascript

Code in Fiddle:

https://jsfiddle.net/AlejandroMoran/416gxk4m/

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.