views:

197

answers:

2

Hello everyone, Im really really new to Javascript but Ive got this script that loads the contents of a url and everything works fine. I call the plannerSpin function with an onClick method on a button but how would I go about displaying an animated gif whilst all this is going on?

var xmlHttp
function plannerSpin(str) {
    xmlHttp = GetXmlHttpObject()
    if (xmlHttp == null) {
        alert("Browser does not support HTTP Request")
        return
    }
    var url = "/recipes/planner/data"
    xmlHttp.onreadystatechange = stateChanged
    xmlHttp.open("GET", url, true)
    xmlHttp.send(null)
}
function stateChanged() {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
        document.getElementById("recipe_planner_container").innerHTML = xmlHttp.responseText
    }
}
function GetXmlHttpObject() {
    var xmlHttp = null;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}
A: 

There are so many ways... for example: you can have the image hidden:

<div id='loading' style='display:none'><img src='img.gif'></div>

and show it as soon as you start the AJAX request:

document.getElementById('loading').style.display = 'inline';

Then, you hide the image again once the request has been completed:

if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete"){
    document.getElementById('loading').style.display = 'none';
    document.getElementById("recipe_planner_container").innerHTML = xmlHttp.responseText;
}   

Or, you can use jQuery, Prototype, Mootools, or whatever JS library you want.

Bye!

Cristian
A: 

You can add the loading gif at the beginning of plannerSpin and remove in the stateChanged function. Somethig like:

var img;
function plannerSpin(str) {
    img=document.createElement("img");
    img.src="image/path";
    //Here you can set some style for the image like an absolute position
    document.body.appendChild(img);
    ....
}


function stateChanged() {
    ...
    document.body.removeChild(img);
}
mck89