Monday, February 26, 2007

Adding a Processing indicator with Prototype.js

Here's a simple method to add a Processing/Loading/Working indicator to indicate when an Ajax request is being processed with prototype.js.

First, define a hidden div (or other preferred HTML element) which will be displayed to indicate that some background processing is going on. Mine happens to look like:

<div id="loading" style="display:none">Loading...
<div style="background-color: white; position: absolute; top: 0px; right: 0px; width: 5px; height: 5px; cursor:pointer;"
onclick="$('loading').hide()"></div>
</div>

In my code, I added another div on the upper right corner which I can click to close this indicator in case something goes wrong with the Ajax event handling which I'll provide in a moment.

I then added a little CSS magic to make it look the way I wanted. In my case, I want the indicator to be on top of everything, centered on the page, with a processing image () on the right side of the text. The background color is white with a double gray border and large, bold font.

#loading {
z-index: 100;
position: absolute;
top: 40%;
left: 40%;
background-image: url("../images/progress-running.gif");
background-repeat: no-repeat;
background-position: 5px;
background-color: white;
padding-left: 25px;
padding-top: 8px;
border-style: double;
border-color: #c0c0c0;
width: 120px;
height: 30px;
font-size: 1.5em;
font-weight: bolder;
}


Ok, so now I have the indicator I want to popup. This can be tailored to your preferences. Now, you simply tell prototype to display it whenever it is processing an Ajax request. This is done by registering some event listeners to the prototype Ajax class.

// register event listeners on the Ajax requests to show/hide the processing indicator
Ajax.Responders.register({
onCreate: function() {
if (Ajax.activeRequestCount === 1) {
$('loading').show();
}
},
onComplete: function() {
if (Ajax.activeRequestCount === 0) {
$('loading').hide();
}
}
});


That's it! Now you should get an indicator whenever you issue an Ajax request that goes away whenever the processing is done.

5 comments:

pir0la said...

hi, thanks man, this really help me...

see ya!

Anonymous said...

Thanks, that was very helpful, works great!

Tony

Dilip said...

I know it has been a while since you posted this article. But it is a nice simple way of showing a processing indicator. Thanks a lot.

Sony AK said...

very good example, clean and it's works!

Phil said...

Looks nice but for the life of me I have no idea where you add in the Ajax.responder.register() code. In the header and call it on page load? Modify the prototype.js file?