Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait with image replace until image is loaded

I have a working script (thanks stackexchange!) for exchanging an image on the fly. I use it as a gallery script. It looks like this:

           $(".source a").click(function(e){
                e.preventDefault();
                var $a = $(this);
                $("#targetcontainer img").hide("puff", function(){
                    $(this).attr("src", $a.attr("href")).show("fold");
                });
            });

The problem regarding this script is that the old image flickers after the JQ show command. The new source Image shows up a second or so later which makes a weird effect. how can I prevent this from happening?

like image 466
cukabeka Avatar asked Nov 30 '22 08:11

cukabeka


2 Answers

You could preload the image before attempting to display it...

$(".source a").click(function(e) {
    e.preventDefault();

    var newSrc = this.href,
        image = new Image();    

    image.onload = function() {
        $("#targetcontainer img").hide("puff", function() {
            $(this).attr("src", newSrc).show("fold");
        });
    }
    image.src = newSrc;
});
like image 74
alex Avatar answered Dec 04 '22 11:12

alex


In JQuery there is load event.

1) Retrieve image.

var image = $("#img");
image.hide();

2) On load do something.

image.load(function(){
 image.show();
});

3) Change src attribute to fire load event after image has changed.

image.attr("src","image.jpg");

You can read more about it in here: http://api.jquery.com/load-event/

like image 34
Jānis Gruzis Avatar answered Dec 04 '22 11:12

Jānis Gruzis