Question

I want to iterate over an array, fading each one in then out. But if an index within that array should contain an array of it's own I want the outer array to stop; then animate it's internal array; then continue.

I have provided a jsfiddle

I know it's all kinds of spaghetti right now, but I plan on turning it into a function that calls another function on the if statement. However right now I am just kind of confused as to how to get it to stop properly.

$(document).ready(function() {

// start
var elements = $('.switch');

elements.each(function(index) {
    var element = $(this);

    setTimeout(function() {
        element.fadeIn(1000, function() {

            if(element.has('.section')){

                var innerEls = $('.section');
                innerEls.each(function(i) {
                    // stuff
                    var inner = $(this);
                    setTimeout(function() {
                        element.stop();
                        inner.fadeIn(1000).delay(2000).fadeOut(1000);
                    }, 4000 * i);
                });
            }

        }).delay(1000).fadeOut(1000);
    }, 2000 * index);

});

});

<div class="switch">This is &lt;div&gt; number 1</div>
<div class="switch">This is &lt;div&gt; number 2</div>
<div class="switch">This is &lt;div&gt; number 3 
    <div class="section">this</div>
    <div class="section">needs to</div>
    <div class="section">show</div>
</div>
<div class="switch">This is &lt;div&gt; number 4</div>
<div class="switch">This is &lt;div&gt; number 5</div>
Was it helpful?

Solution

you can do

switchelements(elements);

function switchelements(e){
    e.eq(0).delay(1000).fadeIn(1000,function(){
        if($(this).children(".section").length>0){
             var inner=$(this).children(".section");
             switchelements(inner);
        }
        else{
            $(this).delay(1000).fadeOut(1000,function(){
                if(e.length>=2){
                    e.splice(0,1);
                    switchelements(e);
                }else{
                    if($(this).parent(".switch").next("switch")){
                        $(this).parent(".switch").delay(1000).fadeOut(1000,function(){
                            switchelements($(this).nextAll(".switch"));
                        });
                    }
                }
            });
        }
    });   
}    

http://jsfiddle.net/x2s8P/3/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top