AJAX: indicate something is happening with animated icon
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.
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:
This works:
- 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> <button onclick="stopBusy();">Stop</button> <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); }
Easy email testing with http://www.ximailstop.com