Appendix JS_C_A11

 

Summary

Requirement: Maintain a logical focus order for interactive components.

Details: Use scripting to re-order content in the DOM.

Examples

Correct code

Refer to the JS_C_A11 live demo for a working example.

<ol id="demo">
    <li><a href="...">New South Wales</a></li>
    <li><a href="...">Victoria</a></li>
    <li><a href="...">Queensland</a></li>
    <li><a href="...">Western Australia</a></li>
    <li><a href="...">South Australia</a></li>
    <li><a href="...">Tasmania</a></li>
    <li><a href="...">Australian Capital Territory</a></li>
    <li><a href="...">Northern Territory</a></li>
</ol>
var list = document.getElementById('demo');
 
function clean(element)
{
    for(var x = 0; x < element.childNodes.length; x ++)
    {
        var child = element.childNodes[x];
        if(child.nodeType == 8 
            || (child.nodeType == 3 
                && !/\S/.test(child.nodeValue)))
        {
            element.removeChild(element.childNodes[x --]);
        }
        if(child.nodeType == 1)
        {
            clean(child);
        }
    }
}
 
clean(list);
 
list.addEventListener('keydown', function(e)
{
    if((e.keyCode == 38 || e.keyCode == 40) && !e.shiftKey) 
    {
        var target = e.target;
        do
        {
            if(target.nodeName.toLowerCase() == 'li')
            {
                break;
            }
        }
        while(target = target.parentNode);
 
        if(target)
        {
            if(e.keyCode == 38 && target.previousSibling)
            {
                target.parentNode.insertBefore(
                     target, 
                     target.previousSibling);
            }
            else if(e.keyCode == 40 && target.nextSibling)
            {
                target.parentNode.insertBefore(
                     target, 
                     target.nextSibling.nextSibling);
            }
            target.firstChild.focus();
 
            e.preventDefault();
        }    
    }
}, false);