Ajax loading overlay with YUI

Posted by – July 7, 2007

First off, let me say that I love Yahoo’s YUI Library. It seems to be very well thought out, and makes many tasks much simpler.

For Example, let say you upgrade your web app with some tasty Ajax. Now lets assume some of these ajax requests are working a little slow. The proper thing to do would be inform the user that something is happening in the background, so they aren’t lost. YUI makes it easy to display an overlay window with a loading image during the requests.

To do this, we use a Panel object. A panel object is basically a DIV with methods to hide and display itself, as well as advanced display options. Here is some starter code:


ajaxLoadingPanel = new YAHOO.widget.Panel("ajaxLoadPanel", {
width:"240px",
fixedcenter:true,
close:false,
draggable:false,
modal:true,
visible:false,
effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
}
);

What we did here is create a basic panel. The first argument is the elements ID. This can either be an ID of an existing DIV in your DOM, or can be a new ID which will be applied to a dynamically created DIV. The next argument is an Object containing configuration options. These are pretty self explanatory: we set a width, tell it to display in the exact middle of the screen, don’t display a close button, don’t allow the user to drag it, make it a model window, and have it fade in and out. (FYI – a model window just means that it fades everything else on screen).

Next, we fill the DIV with content. If you used an ID of a pre-existing DIV, you can skip this code:


ajaxLoadingPanel.setHeader("Loading, please wait...");
ajaxLoadingPanel.setBody(' ');
ajaxLoadingPanel.render(document.body);

Here we simply set the header and body content of the div, and then add it to the DOM as a child of the body tag.

Good News! We are almost done! The panel is created, now all we need to do is trigger it to open, and close. This is done with the following 2 methods:


ajaxLoadingPanel.show();
ajaxLoadingPanel.hide();

All you need to do is call the show method right before your ajax call, and then the hide method right after recieving your ajax response. Thats it!

1 Comment on Ajax loading overlay with YUI

  1. Simon says:

    Thanks for this, it really helped me out today when the YUI site gave examples which were to long for my requirements!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>