Steven
Steven

Reputation: 19445

Not able to cross-fade images correctly using jQuery and CSS3?

I have an image gallery:

enter image description here

My plan is that when I click on of the smaller images, it will fade in on top of the large image.
(see my fiddle)

I want to achieve this using CSS3 transition: opacity 0.8s ease;.

I could use

$(img).appendTo($('.inner-container')).hide().fadeIn()

But that didn't work so well either.

My code:

$('.slides-container img').on('click', function(){
    var url = $(this).attr('src');
    var currentImg = $('.inner-container img');
    var img = $('<img/>').attr({
        src: url,
        class: '',
        alt: '',
        title: ''
    });

    /*
    $(img).appendTo($('.inner-container')).hide().fadeIn(800, function(){
        $(currentImg).remove();
    });
    */

    $(img).appendTo($('.inner-container')).removeClass('hide').promise().done(function(){
        setTimeout(function () {
            $(currentImg).remove();
        }, 800);
    });

});

What am I missing in order to get a smooth fade in?

Upvotes: 0

Views: 69

Answers (2)

drakonli
drakonli

Reputation: 2444

I've created a fiddle where jquery u described works.

$('.click').on('click',function(){
    var img = $(this).find('img').clone().hide();
    var mainContainer = $('.main_container');
    mainContainer.append(img);
    img.fadeIn(800,function(){
        mainContainer.find('img:eq(0)').remove();
    });
});

http://jsfiddle.net/C9G84/1/

Upvotes: 1

Shomz
Shomz

Reputation: 37701

Fix this:

$(img).appendTo...

to this:

img.appendTo...

since it's already declared as a jQuery element.

See it work, the JS way: http://jsfiddle.net/46JQS/3/

Note that I also had to remove the CSS transitions so they don't clash with each other.


And here is the CSS version. For some reason, I also had to add a little timeout before removing the hide class and it works: http://jsfiddle.net/46JQS/6/. I believe it's because the class was removed before the element rendered in the DOM, so the CSS transitions never fired.

I've also removed the promise.

Upvotes: 3

Related Questions