Wednesday, May 21, 2008

Modal Windows with Javascript/CSS

Recently, I had to implement a feedback window while my AJAX code was running in the background, like a modal window in desktop applications. I haven't really seen a simple example to do this. I've seen some stuff but I wanted to tie up everything here.

CSS

#modal {
z-index: 998;
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
display:none;
-moz-opacity: 0.75;
filter: alpha(opacity=75);
background: #CCCCCC;
}

#loading {
z-index: 999;
position: fixed;
top: 40%;
left: 40%;
background-image: url("progress-running.gif");
background-repeat: no-repeat;
background-position: 5px;
background-color: white;
padding-left: 25px;
padding-top: 8px;
border-style: double;
border-color: #c0c0c0;
width: 120px;
height: 30px;
font-size: 1.5em;
font-weight: bolder;
}

HTML

<div id="modal">
<div id="loading" onclick="javascript:document.getElementById('modal').style.display = 'none'">Loading...
<div style="background-color: white; position: absolute; top: 0px; right: 0px; width: 5px; height: 5px;"></div>
</div>
</div>
<div>
<input type="button" name="btn" value="Show Modal Window" onclick="javascript:document.getElementById('modal').style.display = 'block'" />
</div>

As always, we need a tweak for it to run properly in IE, just add the following to the CSS
body{
margin: 0px;
}


Demo Sample 1 from Busydev.Com

Here is second way of doing this. The sample above has a small problem. The modal div showing the "Loading..." is not 100% opaque, it has some filter applied to it. This can be a problem when you need some information to be input by the user before you submit, or requesting to login again after a session timeout. In these cases, it would be more appropriate to display the information fully visible. The sample below uses a separate div for the background, and creates a div for the middle part.

CSS

#modalPage{
display: none;
position: fixed;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
}

.modalBackground{
filter: Alpha(Opacity=80);
-moz-opacity:0.8;
opacity: 0.8;
width: 100%;
height: 100%;
background-color: #999999;
position: fixed;
z-index: 500;
top: 0px;
left: 0px;
}

.modalContainer
{
background-color: white;
border: solid 4px black;
position: absolute;
top: 35%;
left: 38%;
z-index: 1000;
width: 250px;
height: 100px;
padding: 0px;
}

.modalTitle
{
width: 242px;
background-color: #009900;
padding: 4px;
color: #ffffff;
text-align: right;
cursor:pointer;
}

.modalBody
{
padding: 10px;
}

HTML

<div id="modalPage">
<div class="modalBackground"></div>
<div class="modalContainer">
<div class="modalTitle"><a onclick="document.getElementById('modalPage').style.display = 'none';">X</a></div>
<div class="modalBody">
Comment: <input type="text" name="textbox" value="" /> </div>
</div>
</div>

<div>
<input id="Button1" type="button" value="Show Modal Window" onclick="document.getElementById('modalPage').style.display = 'block'" />
</div>

Demo Sample 2 from Busydev.Com

No comments: