In this article I will explain how to display a modal popup window using window.open method in JavaScript.

JavaScript already has ShowModalDialog function but it does not work in all browser and hence I have come up with a trick where using Modal DIV background we can freeze the Parent Page content until Modal Window is closed.

 

Concept

The concept is to open a PopUp and then freeze the parent window and when the popup is closed the parent window is changed back to normal.

 

Parent Page

To start with here is the script that will open a PopUp Window.

<script type = "text/javascript">

    var popUpObj;

    function showModalPopUp()

    {

    popUpObj=window.open("PopUp.htm",

    "ModalPopUp",

    "toolbar=no," +

    "scrollbars=no," +

    "location=no," +

    "statusbar=no," +

    "menubar=no," +

    "resizable=0," +

    "width=100," +

    "height=100," +

    "left = 490," +

    "top=300"

    );

    popUpObj.focus();

    LoadModalDiv();

    }

</script>

<input id="Button1" type="button" value="button" onclick="showModalPopUp()" />

 

You will notice above that I am calling a function LoadModalDiv() which is given below. The job of this function is to freeze the screen using a DIV.

 

<script type = "text/javascript">

    function LoadModalDiv()

    {

        var bcgDiv = document.getElementById("divBackground");

        bcgDiv.style.display="block";

    }

</script>

 

And finally the third function that will unfreeze the parent page by hiding the Modal DIV. This function will be called from the PopUp page in the page unload event which will trigger when the PopUp page is closed.

<script type = "text/javascript">

     function HideModalDiv()

     {

        var bcgDiv = document.getElementById("divBackground");

        bcgDiv.style.display="none";

     }

</script>

 

For freezing the screen I am using a Transparent DIV whose Z-index is set to a value greater than zero so that it overlaps the parent page.

<div id = "divBackground" style="position: fixed; z-index: 999; height: 100%; width: 100%; top: 0; left:0; background-color: Black; filter: alpha(opacity=60); opacity: 0.6; -moz-opacity: 0.8;display:none">

</div>

 

 

PopUp (Child) Page

In the PopUp Page I have written a small script that runs when the PopUp page is closed.

<script type = "text/javascript">

  function OnClose()

  {

    if(window.opener != null && !window.opener.closed) 

    {

       window.opener.HideModalDiv();

    }

  }

  window.onunload = OnClose;

</script>

As you will notice above I am calling the HideModalDiv() function of the parent page when the window unload event is triggered. This will unfreeze the screen as soon as PopUp is closed.

Figure below displays the Demo Modal PopUp Window.

Modal PopUp using JavaScript

Demo

View Demo

Downloads

Download Code (3.23 kb)

 

The above code has been tested in the following browsers

Internet Explorer  FireFox  Chrome  Safari