views:

725

answers:

1

I have an image on a webpage which is being dynamically generated by a server-side CGI program. Periodically this image is refreshed by a timer and/or changed based on user input. So I have a Javascript function like

// <img id="screen" src=""> is elsewhere in the page
function reloadImage() {
    $("#screen").attr("src", make_cgi_url_based_on_form_inputs());
}

This works just fine, but sometimes it takes awhile to load the image. So I'd like for some sort of message to appear that says "Loading image..." but then have that image disappear when the image has loaded and is being displayed in the browser.

Is there any kind of Javascript event that can do this? Alternatively, is there any other way I can load/change/update an image and detect when the loading is finished, through Ajax or whatever else?

+4  A: 

You can try out this jquery solution: http://jqueryfordesigners.com/image-loading/

$(function () {
        var img = new Image();
        $(img).load(function () {
            //$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
            $(this).hide();
            $('#loader').removeClass('loading').append(this);
            $(this).fadeIn();
        }).error(function () {
            // notify the user that the image could not be loaded
        }).attr('src', 'http://farm3.static.flickr.com/2405/2238919394_4c9b5aa921_o.jpg');
    });
marcgg
Thanks! I totally missed the part in the jQuery load documentation where it says that the load function will work on images as well as windows and frames.
Eli Courtwright
Glad I could help :)
marcgg