Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35973

change var into a cascade animation jQuery

I have a cascade animation in jQuery. The problem is that: into the div I have two different element with two different class: linguetta_small, linguetta. If the element to aniamte has class "linguetta" have to be a margin of 5px instead if the class is linguetta_small the margin left have to be 40px. How can I make that? This is my html

<div id="linguetta_next">
    <div class="linguetta" id="linguetta_next1 moved" style="margin-left:100%;">
        <p class="tit_linguetta">azienda</p>
    </div>
    <div class="linguetta_small" id="linguetta_next2 moved" style="margin-left:100%; margin-top:10px; background:#b0f271;">
        <p class="tit_linguetta_small">staff</p>
    </div>
    <div class="linguetta_small" id="linguetta_next3 moved" style="margin-left:100%; margin-top:10px; background:#0a5a0a;">
        <p class="tit_linguetta_small" style="color:#fff;">risorse umane</p>
     </div>
 </div>

And this is my jQuery code:

function movePageCenter(id, old_id) {
    var margin = "1%";
    $("#linguetta_next div").each(function(i) {
        var el = $(this);
        setTimeout(function() {
            el.animate({
                marginLeft: margin
            }, 400, function() {
                if (el.next(".linguetta_small").hasClass('linguetta_small')) {
                    margin = "40px";
                }
                else {
                    if (el.next(".linguetta").hasClass('linguetta')) {
                        margin = "5px";
                    }
                }
            });
        }, i * 200);
    });

});
}

Upvotes: 1

Views: 122

Answers (1)

Tosh
Tosh

Reputation: 1857

With each() we loop through each elemeat that fits our selection. You don't have to consider the element that is next in line to be animated, you treat every element seperately.

So with every element we check which class it has and set the margin accordingly.

Also jQuery has a very nice function called delay, which is much easier to use than the setTimeout function.

$("#linguetta_next div").each(function(i) {

       var $el = $(this);
       var margin;   

       if ($el.hasClass('linguetta_small')) {
           margin = 40;
        } else {
           margin = 5;
       }


        $el.delay( i * 200).animate({ 'margin-left': margin }, 400);
});

Upvotes: 1

Related Questions