Dialog Focus: Keep it modal

From Level Access Web Labs
Revision as of 16:28, 18 May 2016 by Bbroughton (talk | contribs)
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')) {
        e.onkeydown = function (event){
            if (event.keyCode === 9) {//tab key
                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';
    function openDialog() {
        modal.className = 'modal open modal-control';