DOM Elements focus testcase
HTML
<!-- See http://www.quirksmode.org/dom/events/index.html for more info... -->
<!-- inputs & textareas -->
<p><input id="field-text" type="text" name="name" /></p>
<p><input type="checkbox" name="ck" /></p>
<p><input type="radio" name="rd" /></p>
<p><textarea name="descr"></textarea></p>
<!-- link -->
<p><a id="my-link" href="#">I am a link</a></p>
<p><a id="my-link-tabindex" href="#" tabindex="0">I am a link with tabindex 0</a></p>
<p><a id="my-link-tabindex" href="#" tabindex="-1">I am a link with tabindex -1</a></p>
<!-- div with tabindex=0 -->
<div id="my-div" class="box" tabindex="0">I am a focusable box</div>
<!-- nested focusable elements? (with tabindex) -->
<div class="box" tabindex="0">
I am a focusable box
<div class="box" tabindex="0">
And I am a nested box inside that top box
</div>
</div>
<!-- several buttons to programmatically trigger focus -->
<button id="btn-focus-text">Focus text input</button>
<button id="btn-focus-link">Focus link</button>
<button id="btn-focus-link-tabindex">Focus link with tabindex</button>
<button id="btn-focus-div">Focus div</button>
CSS
body {
margin: 20px;
}
p {
margin: 10px 0;
}
.box {
border: dashed 1px green;
padding: 5px;
margin: 10px 0;
}
JavaScript
/**
* document.getElementById() shorthand
*/
function get(id) {
return document.getElementById(id);
}
document.addEventListener('focus', function(e) {
console.log('Focus! e =', e,
' e.target =', e.target,
' document.activeElement =', document.activeElement);
}, true); // use event capturing as focus events aren't bubbled
get('btn-focus-text').addEventListener('click', function() {
get('field-text').focus();
}, false);
get('btn-focus-link').addEventListener('click', function() {
get('my-link').focus();
}, false);
get('btn-focus-link-tabindex').addEventListener('click', function() {
get('my-link-tabindex').focus();
}, false);
get('btn-focus-div').addEventListener('click', function() {
get('my-div').focus();
}, false);