Search code examples
jquerytoggleblock

Toggle Classes with delays


I have 4 blocks and I want script to add classes with a delay: appears 1 block, then 2nd and so on. here is the code:

$(‘#about’).click(function() {
    $(‘.front’).toggleClass(‘open-front’);
    $(‘.back’).toggleClass(‘open-back’);
});

Before:

Before

...and After:

After http://eyes.in.ua/wp-content/uploads/2014/07/question-2.png

See this color block that after click becomes black. They are four. But I want 1 block appear 1st, then the delay 600ms and script adds classes to 2nd block, then delay 1200ms and script adds to 3rd block classes. Thats what I want.

Pardon me, if I didn't explain it correctly...

Got any ideas?


Solution

  • You mean something like this?

    $('#about').click(function() {
        $('.front').toggleClass('open-front');
        setTimeout(function() {
            $('.back').toggleClass('open-back');
            setTimeout(function() {
                $('.third').toggleClass('open-third');
            }, 600);
        }, 600);
    });
    

    Or something like this?

    $('#about').click(function() {
        var delay = 600;
        $('.front').each(function(i, e) {
            setTimeout(function() {
              $(e).toggleClass('open-front');
            }, i * delay);
        });
        $('.back').each(function(i, e) {
            setTimeout(function() {
              $(e).toggleClass('open-back');
            }, i * delay);
        });
    });