Monday, August 2, 2010

JavaScript: Modal Windows

Internet Explorer adds an entirely new method to the window object to open a modal window - window.showModalDialog(). If you use that to try to open a modal window then if your visitor is running Internet Explorer then a modal window will be opened. If they are running some other browser then all they will get is a Javascript error.

The Mozilla based browsers (Netscape 6+, Firefox, etc) use a completely different method to declare that the window that is opened should stay in front . They use the normal and just add an extra attribute modal=yes to the list of atributes that define the appearance of the window (unfortunately it still doesn't actually make it modal it just forces it to stay in front which is the best that you can do with these browsers). If you try to use this to try to open a modal window then the window will open in any browser (provided that it hasn't been blocked by a popup blocker) but it will only stay in front if the browser is one of the Mozilla based family. If your visitor is running Netscape 4, any version of Opera, or Internet Explorer etc. then the window will still open it just wont stay in front.

The best that we can do to set up a window that is as modal as we can make it is to combine these two together to create code that will open a modal window in Internet Explorer, keep the window in front in Mozilla based browsers, and which will just open a non-modal window in those browsers that don't support modal windows. Of course we don't want to test which browser that the browser itself claims to be since most Opera browsers are set to report that they are Internet Explorer. Instead we test for support for the showModalDialog method itself to identify those versions of Internet Explorer that support it. Combining the code together gives us the following (with the amendments from an ordinary non-modal window shown in bold).


function modalWin() {
if (window.showModalDialog) {
} else {'xpopupex.htm','name',
menubar=no,scrollbars=no,resizable=no ,modal=yes');


Calling Example :

<a href="xpopupex.htm" target="name"
onclick="modalWin(); return false;">click here</a>

If you want to see what effect that using all of the above code has in your particular browser then click here

For more details and examples :

Author : Stephen Chapman

No comments:

Post a Comment