Tallboy
Tallboy

Reputation: 13467

css3 image fadein

I'm trying to have images fade in with css3 once they're loaded. The problem is the way my methods are currently chained it fades it in and out for a split second twice. instead of just being blank and fading in.

my solution was to try and split out the animation code into a seperate class that i apply AFTER i initially set the opacity to zero (i do this in JS so people without js enabled can still see the images).

It's still not working though

I assume its because in this code its setting the opacity to zero and immediately adding an animation transition class which somehow catches the opacity .css() method while its changing still (dont know how this is possible,... shouldnt it complete opacity before moving on to add class?)

// nice thumbnail loading
$('.thumb').css('opacity','0').addClass('thumb-animated').on('load', function(){
    $(this).css('opacity','1');
});   


.resources .thumb-animated {
    -webkit-transition: opacity .2s;
       -moz-transition: opacity .2s;
        -ms-transition: opacity .2s;
         -o-transition: opacity .2s;
            transition: opacity .2s;
}   

Upvotes: 4

Views: 234

Answers (4)

XCS
XCS

Reputation: 28177

Well...

Why do you set opacity to 1 in jQuery? If you want to use CSS3 and not simply fadeIn(200) why don't you add "opacity: 1" to css class thumb-animated?

EDIT:

Note that load will not be triggered if the image is already in cache.
Also, !important has to be added to rewrite the rule modified via javascript.

There you go: http://jsfiddle.net/enTCe/5/ This seems to work perfectly outside JSfiddle, on JSfiddle looks like it waits for all the images to be loaded.

Upvotes: 1

sleepwalker
sleepwalker

Reputation: 1032

What about using just css animations? No JS code is needed.

        @-webkit-keyframes opacityChange {
            0%   { opacity: 0; }
            100% { opacity: 1; }
        }
        @-moz-keyframes opacityChange {
            0%   { opacity: 0; }
            100% { opacity: 1; }
        }
        @-ms-keyframes opacityChange {
            0%   { opacity: 0; }
            100% { opacity: 1; }
        }
        .thumb {
            width: 200px;
            height: 200px;
            opacity: 1;
            -webkit-animation: opacityChange 5s;
            -moz-animation:    opacityChange 5s;
            -ms-animation:     opacityChange 5s;
        }

Upvotes: 1

Andreas Louv
Andreas Louv

Reputation: 47127

You can wait adding the class to the image is loaded

$('.thumb').css('opacity','0').on('load', function(){
    $(this).addClass('thumb-animated').css('opacity','1');
});

Upvotes: 0

Farahmand
Farahmand

Reputation: 2991

Try something like this:

$('#thumb').hide();

myImg = $('<img>').attr('src', 'thumb.png').load(function(){
    $('#thumb').html(myImg).fadeIn(200);
});

Upvotes: -1

Related Questions