I have a modal window script that we are trying to bring up to speed for accessibility requirements. The requirement says that when you tab away from the window, it should close. It also says that upon dismissing the window, the original triggering element must get focus back.
After doing some digging I found this: jQuery figuring out if parent has lost 'focus'. It seemed that the easiest way to tell when you've tabbed away from the window is to track the focusin event, and when focus fires on an element that is not a child of the open modal, dismiss the window. This method however, is problematic as you'll see (not to mention a little too heavy for my liking). Here is the code that handles this:
$('body').focusin(function(e) {
if (!$(e.target).parent().is('.current-window')) {
closeModal();
}
});
and the function that closes the window:
function closeModal() {
$('.modal-mask, .current-window').fadeOut('fast', function(){
$(this).removeClass('current-window');
$('.modal-mask').removeAttr('style');
$('.modal-trigger').focus();
});
}
Now obviously, when I run this code, closeModal() fires back and forth between the focusin event up to the maximum call stack and therefore throws the "maximum call stack exceeded" error message before giving focus to the triggering element.
Refer to this fiddle for full code: http://jsfiddle.net/pbredenberg/wxX4T/
I'm trying to think of a better way to handle this requirement, or at the very least avoid the infinite loop. Can anyone point me in the right direction?