Dialog Focus: Keep it modal

From Level Access Web Labs
Jump to navigation Jump to search

Dialog Focus - Keeping focus inside modal dialogs.

Dialog Focus - Keeping focus inside modal dialogs.

While the dialog is open, focus cannot move out of the dialog.

A control before the dialog Open the dialog A control after dialog

The Javascript


    
    var modal = document.getElementsByClassName('modal')[0];
    var controls = modal.getElementsByClassName('modal-control');

    function modalShift(e,f,g){
    //handle focus between modal elements
        //e - current element
        //f - next element
        //g - previous element
        e.onblur = function (event) {//in case user clicks out of dialog
            //important that all modal controls have this class 'modal-control'
            setTimeout(function () {
                if (!document.activeElement.classList.contains('modal-control')) {
                    event.target.focus();
                }
            },10);
        }
        e.onkeydown = function (event){
            if (event.keyCode === 9) {//tab key
                event.preventDefault();
                if (event.shiftKey) {
                    g.focus();//previuos control
                } else {
                    f.focus();//next control
                }
            }
        };
    }
    
    //middle controls
    for (var i=1,j=controls.length-1;i < j; i++){
        modalShift(controls[i], controls[i+1], controls[i-1]);
    }
    //first control
    modalShift(controls[0], controls[1], controls[controls.length-1]);
    //last control
    modalShift(controls[controls.length-1], controls[0], controls[controls.length-2]);
    
    function closeDialog() {
        modal.className = 'modal closed modal-control';
        document.getElementsByClassName('modal-launcher')[0].focus();
    }
    
    function openDialog() {
        modal.className = 'modal open modal-control';
        modal.setAttribute('tabindex','-1');
        modal.focus();
    }