Image Loading with JavaScript

So you want to show "Now Loading", or a simple message while your images are loading on your webpage? then its pretty simple.

Many developers these days are using jQuery to achieve these effect's, Good news is you dont need any 3rd party library to create a loading effect with javaScript.

here is how you do it.

Create a Div which will hold image. and assign some styles to it.

#holder {
 width:500px;
 height:500px;
 border:solid 1px #000000;

}

<div id="holder" class="loading">

Assign a Class to it, and set its backgroung image to a loading gif.


.loading {
 background:url("loading.gif") no-repeat center;
}

Now create a function which will populate Div with your image.

 <a href="javaScript:LoadIT();">Load Brock</a>

And here is the Code for the function...

 var img,t

 function LoadIT() {


   img = new Image();
   img.src = "Vactions.jpg"  // Change it to whatever Image you want
   Loader()
  

 }


 function Loader() {

 
 if(img.complete) {
   document.getElementById("holder").appendChild(img)
  clearTimeout(t)
  return;
 }

   t = setTimeout("Loader()", 1000)
}

 

So Basicly the idea is... you use a Background image for a DIV and then use javaScript's img.COMPLETE function combined with setTimeout to place image into a container.

Here is full source code...

 

<style>


#holder {
 width:500px;
 height:500px;
 border:solid 1px #000000;

}

.loading {
 background:url("loading.gif") no-repeat center;
}

</style>

<script>

 var img,t

 function Brock() {


   img = new Image();
   img.src = "eliza.jpg"
   Loader()
  

 }

 


 function Loader() {

 
 if(img.complete) {
   document.getElementById("holder").appendChild(img)
  clearTimeout(t)
  return;
 }

   t = setTimeout("Loader()", 1000)
}

</script>

<body>

 <a href="javaScript:Brock();">Load Brock</a>


 <div id="holder" class="loading">

 </div>

</body>
 

Posted by:

No comments posted.

Name :  

Email :  

Comment Below