Wednesday, March 10, 2010

AJAX Animation using jQuery

During an AJAX call from a website, usually the screen won't blink - because page is not refreshing. This is neat because it gives the impression to the user that their interaction with the site to be seamless and uninterrupted.

But sometimes, you do want to give a visual clue to the user that an action is happening and you want them to know about it. Maybe by giving them an hourglass or a "loading ..." clue etc. So how do you do this easily? This post is about using jQuery to provide visual clue to the user on AJAX requests.

First, obviously you will need to reference jQuery library. I usually use the one hosted in Google:
 <script src="" type="text/javascript"></script>
Add the HTML to display our visual clue. In this example I am displaying a black bar on the top of the browser, about 25px in height that has a "Loading ..." text in it. So when an AJAX call is happening, this black bar will be displayed until the call is done.
 <div style="z-index:101; width:100%; height:25px; position:fixed; left:0px; top: 0px;">
<div id="loadingbar" style="height:25px;display:none; margin-left:auto; margin-right:auto; background-color:#000000; color:#fff">
  Loading ...</div>
<div class="stretch"> </div>
Now we add the javascript to show and hide the bar, plus I also like to gray out the background a little bit.
 $(document).ready(function() {
    jQuery().ajaxStart(function() {
        $("body").fadeTo("fast", 0.70);
    jQuery().ajaxStop(function() {
        $("body").fadeTo("fast", 1.0);

Done. Now anytime there is an AJAX call in your page, the background will be grayed out a little bit and a black bar will show up on the top. To increase/decrease the opacity of the background during the graying out, you can adjust the value on the "fadeTo" call. Currently it is set to "0.70" or 70%. If you want less transparency (or more grayed out), then set it lower (between 0.00 to 1.0), and set it higher for less transparency.

No comments: