jQuery: Flash loader

In this post I will show you how to create a simple Flash loader with jQuery. As you will see, everything is performed by a simple JavaScript timer with a progressively incremented counter. The remaining part of our example is made up of our CSS styles. Let's start with our CSS styles first:

html, body {
 margin: 0;
 padding: 0;
 height: 100%;
 width: 100%;
 min-height: 100%;
}

body {
 position: relative;
}

#overlay {
 width: 100%;
 height: 100%;
 position: absolute;
 top: 0;
 left: 0;
 background: #444;
}

#loader {
 width: 160px;
 height: 20px;
 position: absolute;
 top: 50%;
 left: 50%;
 margin: -10px 0 0 -80px;
 background: #fff;
}

#loader span {
 width: 0px;
 display: block;
 height: 20px;
 background: #d40;
}

We've set our styles for an overlay element and our loader, both absolutely positioned. To create the loading effect, we've inserted an empty element within our loader and zeroed its width. This width will be later incremented in our timer by the animate() method:

$(function() {
  $('<div id="overlay"/>').css('opacity', '0.5').
  appendTo('body').hide();
  $('<div id="loader"/>').appendTo('body').hide();
  $('<span/>').appendTo('#loader');
  
  setTimeout(function() {
  
     $('#overlay, #loader').show();
     
     var counter = 0;
     
     var interval = setInterval(function() {
     
       counter++;
       
       if(counter == 10) {
       
         clearInterval(interval);
         $('#overlay, #loader').hide();
         $('span', '#loader').css('width', '0px');
       
       
       }
       
       $('span', '#loader').animate({
         width: '+=16px'
       });
       
      
     
     }, 500);
  
  
  }, 50);


});

When the internal counter reaches 10, we reset it and hide all the elements, plus restoring the original width of the inner element of our loader. You can see the demo below.

Demo

Live demo

Leave a Reply

Note: Only a member of this blog may post a comment.