3

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?

1

1 Answer 1

9

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');
    });
1
  • 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. Sep 4, 2009 at 17:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.