JavaScript: modal dialog
September 07, 2008 22:10:21 Last update: September 07, 2008 22:15:51
When you use window.open to open a page in a new browser window, the new window is not modal, i.e., focus on the new window can be lost when the parent window is clicked. IE provides
This is a JavaScript that makes the popup window modal. The central trick is to check focus periodically with
To make the HTML page modal:
window.showModalDialog but it doesn't have the full power of a real browser window, and it's IE specific.
This is a JavaScript that makes the popup window modal. The central trick is to check focus periodically with
window.setInterval and request focus when it's lost. In IE, when an input on the page gets focus, the window thinks that it lost focus and requests focus back, thus taking focus away from any input fields - making it impossible to enter data into input fields in the modal dialog. This problem is solved by attaching onfocus and onblur handlers to all input fields on the page.
function setModal(m) { var intervalId; var _gotFocus = false; if (m) { var inputTags = [ "INPUT", "SELECT", "TEXTAREA", "BUTTON" ]; var inputs = new Array(); for (var k = 0; k < inputTags.length; k++) { var elems = document.getElementsByTagName(inputTags[k]); for (var j = 0; j < elems.length; j++) { inputs.push(elems[j]); } } for (var k = 0; k < inputs.length; k++) { inputs[k].onfocus = function() { _gotFocus = true; }; inputs[k].onblur = function() { _gotFocus = false; }; } intervalId = window.setInterval(keepFocus, 50); } else { if (intervalId) { window.clearInterval(intervalId); } } function keepFocus() { if (window.closed) { window.clearInterval(intervalId); } else { if (! _gotFocus) { window.focus(); } } } }
To make the HTML page modal:
<html> <head> <script type="text/javascript" src="modalDialog.js"></script> </head> <body onload=setModal(true)> <!-- Page content here --> </body></html>