Difference between revisions of "Dialog Focus: Keep it modal"
Jump to navigation
Jump to search
Dialog Focus - Keeping focus inside modal dialogs.
Bbroughton (talk | contribs) m |
Bbroughton (talk | contribs) m |
||
Line 67: | Line 67: | ||
function closeDialog() { | function closeDialog() { | ||
− | modal.className = 'modal closed | + | modal.className = 'modal closed'; |
document.getElementsByClassName('modal-launcher')[0].focus(); | document.getElementsByClassName('modal-launcher')[0].focus(); | ||
} | } | ||
function openDialog() { | function openDialog() { | ||
− | modal.className = 'modal open | + | modal.className = 'modal open'; |
modal.setAttribute('tabindex','-1'); | modal.setAttribute('tabindex','-1'); | ||
modal.focus(); | modal.focus(); |
Latest revision as of 16:32, 18 May 2016
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 dialogThe 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();
}