views:

156

answers:

1

Hello,

Not sure if I am doing this correctly or not.

Here is my JS:

    var currentIMG;
     $( '.leftMenuProductButton' ).hover (
            function () {

                currentIMG = $("#swapImg").attr("src");
                var swapIMG = $(this).next(".menuPopup").attr("id");


               $("#swapImg").css("opacity", 0).attr("src", productImages[swapIMG], function(){
                    $("#swapImg").fadeTo("slow", 1);

                                                                                    });


            },
            function () {


                $("#swapImg").stop().attr("src",currentIMG);

    });

What I am trying to do is Set a IMG Opacity to 0 (#swapImg), replace it's SRC, then fade it back in. So I am trying to fade it back in using a callback from the attr().

If I am doing this incorrectly, can someone please explain a better way to do this? The reason I am trying to do it in the callback is that I need the fadeTo to only occur after the new image is fully loaded, otherwise it does a bit of a flash.

I am using jquery 1.4, and according to http://jquery14.com/day-01/jquery-14 it appears you can do a callback in the attr() method.

+1  A: 

You can do this with the load event like this:

$("#swapImg").css("opacity", 0).attr("src", productImages[swapIMG])
             .one("load",function(){ //fires (only once) when loaded
                $(this).fadeIn("slow");
             }).each(function(){
                if(this.complete) //trigger load if cached in certain browsers
                  $(this).trigger("load");
             });

The fade will start after the image load event fires.

Nick Craver
Huh! That's a neat trick. (Out of votes. :| )
D_N
Yeah I ran your first version, and apparently Chrome was caching it and it wasn't working. This version works.
Jared
Just a note, `fadeIn()` I believe is designed if the element has `display:none`, and not for just changing the opacity. `FadeTo()` is the only thing that seems to work for me. Thanks for your help!
Jared