AJAX: indicate something is happening with animated icon 

Joined:
04/09/2007
Posts:
727

August 21, 2007 21:25:58    Last update: January 10, 2011 22:19:09
You can grab some animated icons here: http://mentalized.net/activity-indicators/. And here's some code to demonstrate how to use such an icon.

  • Code
  • Demo
<html>
<head>
	<script language="JavaScript" type="text/javascript">
	function startBusy() {
		var icon = document.getElementById("busyicon");
		icon.style.display = '';
		window.onmousemove = followMouse;
		window.onmouseclick = followMouse;
		document.body.onmousemove = followMouse;
		function followMouse(event) {
			var event = event || window.event;
			icon.style.top = event.clientY + document.body.scrollTop + 5 + 'px';
			icon.style.left = event.clientX + document.body.scrollLeft + 15 + 'px';
		}
	}

	function stopBusy() {
		var icon = document.getElementById("busyicon");
		icon.style.display = 'none';
		window.onmousemove = null;
		window.onmouseclick = null;
                document.body.onmousemove = null;
	}

	</script>
</head>
<body>
	<button onclick="startBusy();">Start</button>&nbsp;
	<button onclick="stopBusy();">Stop</button>&nbsp;
	<div id="busyicon" style="position:absolute;top:-100px;left:-100px;display:none"><img src="http://mentalized.net/activity-indicators/indicators/pascal_germroth/indicator.white.gif"/></div>
</body>
</html>


However, if you use Ajax and send a synchronous request, the icon won't show up at all, i.e., the following code doesn't work:

function eventHandler() {
    startBusy();
    var req = getXMLHTTPRequest();
    req.open("GET", url, false);
    req.send(null);
    // handle Ajax response here
    stopBusy();
}


This works:
function eventHandler() {
    startBusy();
    var req = getXMLHTTPRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            stopBusy();
            // handle Ajax response here
        }
    }
    req.open("GET", url, true);
    req.send(null);
}
Share |
| Comment  | Tags
 
Easy email testing with http://www.ximailstop.com