3

I have this code by which I am changing main image on click of thumbnails

$(".thumb").click(function() {
    $("#mainimage").attr("src", $(this).attr("alt"));
});

I want to show wait gif while the news image loads. thanks

techansaari
  • 375
  • 1
  • 5
  • 20

1 Answers1

3

Use .load. This event is fired when the image has finished loading, you could hide your loading gif in this event handler

$("#mainimage").load(function(){
   //Hide your wait gif
});

Show your loading gif before setting the src

$(".thumb").click(function() {
    //show your wait gif
    $("#mainimage").attr("src", $(this).attr("alt"));
});

Update: This would not work if the image is cached and the event won't trigger.

Can cease to fire for images that already live in the browser's cache

A simple workaround is appending a random string to prevent caching

$(".thumb").click(function() {
        //show your wait gif
        $("#mainimage").attr("src", $(this).attr("alt") + "?" + Math.random());
    });

This may have performance hit, but it works

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • I think you want, `$("body").on("load", "#mainimage", function() { ... });` since the src is changing which will trigger another `.load()` event for that element. – Solomon Closson Sep 10 '13 at 02:47
  • @Solomon Closson: thanks for the suggestion, this is also an option using delegated event to deal with dynamically generated elements. – Khanh TO Sep 10 '13 at 02:48
  • What I'm trying to say, is that this will not work after the initial image loads. When you change the src value of the image, it will not trigger `.load()` again. I don't even think delegated event will work either. You will most likely have to create a new image object and than it should work. – Solomon Closson Sep 10 '13 at 02:59
  • @techansaari: I guess the problem is browser cache, when you reload an image from the cache, the event won't trigger. – Khanh TO Sep 10 '13 at 03:36
  • Then if the image is loaded from the cache, there will certainly be no need to display the loading gif. – Simón Sep 10 '13 at 03:48
  • @techansaari : check my updated answer with a simple solution to prevent caching. – Khanh TO Sep 10 '13 at 03:48