user1477535
user1477535

Reputation: 103

Cross Fade animation

I would like the top_content function to cross fade with #test and #test1. Right now the divs #test, and #test1 are using a simple toggle but I would like them both fade out and in at same time.

$(document).ready(function () {
    $('#test, #test1').hide();
    $('.home').click(function () {
        var id = $(this).html().toLowerCase();
        var $top_content = $('#' + id + ':not(:visible)');
        if ($('.current').length === 0) {
            toggleContent($top_content);
        } else {
            $('.current').toggle(400, function () {
                toggleContent($top_content);
            });
        }
    });

    function toggleContent(top_content) {
        top_content.toggle(400);
        $('.current').removeClass('current');
        top_content.addClass('current');
    }
    $("a.home").click(function () {
        $('.active').not(this).removeClass('active');
        $(this).toggleClass('active');
    });
});

http://jsfiddle.net/FJ8DV/

Upvotes: 3

Views: 247

Answers (1)

nnnnnn
nnnnnn

Reputation: 150080

The reason you're not getting a "cross fade" effect is this code:

        $('.current').toggle(400, function () {
            toggleContent($top_content);
        });

You've placed the call to your toggleContent() function in the callback that is called on completion of the .toggle() - so the fade in doesn't happen until the previous fade out is finished. Move that out of the callback and it won't wait for completion thus allowing the animations to happen simultaneously:

        $('.current').toggle(400);
        toggleContent($top_content);

Also, I assume "cross fade" means the elements should appear in the same place at the same time, so you'll need to give them position:absolute styling:

#top_content div { position : absolute; }

Given that you're talking about a cross fade, you might like to replace .toggle() with fadeToggle() as shown in this update to your demo (I've also used a longer delay so the fade is more obvious): http://jsfiddle.net/FJ8DV/1/

Upvotes: 2

Related Questions