1 var focusedElement = null;
3 var modal = document.getElementById('modal');
4 var dialog = document.getElementById('dialog');
5 var body = document.getElementById('global');
6 var html = document.documentElement;
8 var modalShowing = (html.className === 'modal');
11 // Have to hack for Safari, due to poor support for the focus() function.
13 var isSafari = window.navigator.vendor.match(/Apple/);
18 var dialogFocuser = document.createElement('a');
19 dialogFocuser.href="#";
20 dialogFocuser.style.display='block';
21 dialogFocuser.style.height='0';
22 dialogFocuser.style.width='0';
23 dialogFocuser.style.position = 'absolute';
24 dialog.insertBefore(dialogFocuser, dialog.firstChild);
26 dialogFocuser = dialog;
29 window.onunload = function () {
30 dialogFocuser = focusedElement = modal = dialog = body = html = null;
33 var onfocus = function (e) {
34 e = e || window.event;
35 var el = e.target || e.srcElement;
37 // save the last focused element when the modal is hidden.
38 if ( !modalShowing ) {
43 // if we're focusing the dialog, then just clear the blurring flag.
44 // else, focus the dialog and prevent the other event.
45 var p = el.parentNode;
46 while ( p && p.parentNode && p !== dialog ) {
50 dialogFocuser.focus();
56 var onblur = function () {
57 if ( !modalShowing ) {
58 focusedElement = body;
62 html.onfocus = html.onfocusin = onfocus;
63 html.onblur = html.onfocusout = onblur;
65 html.addEventListener('DOMFocusIn',onfocus);
66 html.addEventListener('DOMFocusOut',onblur);
68 // focus and blur events are tricky to bubble.
69 // need to do some special stuff to handle MSIE.
72 function toggleModal (b) {
74 if (modalShowing && b) return;
75 if (!modalShowing && !b) return;
77 html.className=modalShowing?'':'modal';
79 modalShowing = !modalShowing;
83 } else if (focusedElement) {
85 focusedElement.focus();