25 July 2007

Creating Hourglass cursor in Web-Applications

Very often, in most of the windows application, there is a functionality in which the mouse cursor changes to hour-glass whenever the application is doing some background processing or is busy. This is done to give user an intimation to wait for application to finish processing.

We had a similar requirement in one of our web-applications. In the application, the mouser cursor has to be changed to hour-glass when user clicks on a particular button or whenever post-back happens. The cursor has to return back to normal as soon as the processing of the page finishes.

We achieved this functionality using JavaScript and HTML.

For this first we write a JavaScript function which changes the mouse cursor to hour-glass.

function ChangeToHourGlass()
{
document.body.style.cursor = 'wait';
}


Now we need to call this function appropriately so that the required effect is achieved. So we call this function in two page events – onbeforeunload and onunload. This is done by adding these events handlers in the “body” tag of your ASPX/HTML page.

<body onbeforeunload="ChangeToHourGlass();" onunload="ChangeToHourGlass ();">

Now let’s explain in short about both these event handlers:-

Onbeforeunload – This event is fired before a page is getting unloaded.
OnUnload – This event is fired just before the page is getting unloaded.

How the actual functionality works:-

When we click on a submit button in a page, the current page is unloaded. So one of these events is fired and the mouse cursor changes to hour-glass. While the request goes to back-end and returns back with the result, the current page continues to display. So mouse cursor appears as hour-glass. As soon as the back-end processing is finished, the page is re-created in which the mouse cursor returns back to normal. Hence the desired functionality is achieved.

The reason for using both these event handlers is that Internet Explorer browser prefers “Onbeforeunload” event while other browsers prefer “OnUnload” event. So to make this functionality work in all types of browsers, the JavaScript function is called in both these events.

1 comment:

Dr. Device said...

Thanks for the post. This is exactly what we needed on one of our web apps and it's simple enough to implement without breaking any existing code.