Search code examples
javascriptjquerycssanimationdelay

Animate each text lines


$("span").click(function(){
$("div").fadeToggle();
});

$("span").click( function(){
    $("a").css({ opacity: '0' });
    $(".text1").delay(200).animate({ opacity: '1' });
    $(".text2").delay(400).animate({ opacity: '1' });
    $(".text3").delay(600).animate({ opacity: '1' });
});

I want to animate my text in the following way:

When you click on the "CLICK HERE" text, the links in the pink div should animate. Each line should fade in, one after the other.

However, I think my code is wrong, because if you click the "CLICK HERE" text several times in quick succession, animation build up occurs.

How should I fix this?

http://jsfiddle.net/XdLzp/


Solution

  • You have to stop the animation queue on the items e.g.

    <a class="content-toggle" href="#">CLICK HERE</a>
    
    <div class="content">
        <div>TEXT 1</div>
        <div>TEXT 2</div>
        <div>TEXT 3</div>
    </div>
    
    $('.content-toggle').on('click', function(e) {
        e.preventDefault();
    
        var content = $('.content');
    
        // Stop any ongoing animations and hide children.
        content.finish().children().finish().hide();
    
        content.fadeToggle(400, 'swing', function() {
            animateChildrenIn(content);
        });
    });
    
    function animateChildrenIn(parent) {
        parent.children().each(function(i) {
            $(this).delay((i + 1) * 200).fadeIn(800); 
        });
    }
    

    Fiddle: http://jsfiddle.net/4RW5d/