Thursday, May 5, 2011

Loading image while waiting

Sometimes we want to show kind of a "waiting" image while a page is been rendered or while we are waiting for a server response.
It's easy, we just need: some css style, a .gif image, a javascript.
Following code is supporting cross-browsing:

The css classes:

.loadingDiv 
{
z-index: 1000;
position:relative;
top:1200px;
float: left;
width:100%;
background-color:White;
opacity: 0.7;
padding-top:300px;
margin-top:-1200px;
}

.loadingImage
{
margin-left: auto;
margin-right:auto;
padding-bottom:600px;
}


Here are the div and the img element. Place them in the top of the page inside the body tag:

<div id="loading" class="loadingDiv"> 
<img id="imgMainLoadImage" src="../images/loading.gif" border="0" alt="" class="loadingImage" />
</div>


Here is the script. Place it just below the div, no matter if you have any other block of scripts in other sections in the page.

<script> 
var ld = (document.all);
var imgL = (document.all);
var ns4 = document.layers;
var ns6 = document.getElementById && !document.all;
var ie4 = document.all;
if (ns4) {
ld = document.loading;
imgL = document.imgMainLoadImage;
}
else if (ns6) {
ld = document.getElementById("loading").style;
imgL = document.getElementById("imgMainLoadImage").style;
}
else if (ie4) {
ld = document.all.loading.style;
imgL = document.all.imgMainLoadImage.style;
}

function init() {
if (ns4) {
ld.visibility = "hidden";
}
else if (ns6 || ie4) {
ld.display = "none";
}
}

function ShowLoadingImage() {
if (ns4) {
ld.visibility = "visible";
}
else if (ns6 || ie4) {
ld.display = "block";
}
}
</script>


The last and not least part is to call the javascript function in the "onload" event in the body.
I have used this in masterpages as well as content pages.

<body onload="init();"> 

No comments:

Post a Comment