Lucas Santos
Lucas Santos

Reputation: 1369

How can I increment a css top value of multiple elements at different times?

So I have been trying to get this functionality to work but has been giving me trouble.

JsFiddle: https://jsfiddle.net/Lm30zcxf/

HTML:

<div class="container">

    <button>CLICK</button>

    <div class="circle circle-1"></div>
    <div class="circle circle-2"></div>
    <div class="circle circle-3"></div>
    <div class="circle circle-4"></div>
    <div class="circle circle-5"></div>

</div>

CSS

.circle{
    width: 40px;
    height: 40px;
    position: absolute;
    background: red;
    border-radius: 100%;
}

.circle-1{ top: 10em; left: 10em; }

.circle-2{ top: 20em; left: 20em; }

.circle-3{ top: 30em; left: 30em; }

.circle-4{ top: 40em; left: 40em; }

.circle-5{ top: 50em; left: 50em; }

button{ padding: 10px 50px; display: table; margin: auto; }

Javascript:

$(document).ready(function(){
    $("button").click(function(){
        //move each circle down out of screen one at a time

        //then after about 3 seconds have them appear in the same spot they were initially in
    });
});

My Goal:

Upvotes: 1

Views: 838

Answers (2)

charlietfl
charlietfl

Reputation: 171669

Something like this will get you started. By using index in loop can increment animation delay

$("button").click(function(){
    var top =$(window).height(),// amount to offset
        $circles = $('.circle'),
        numCircles = $circles.length;

    $circles.each(function(i, elem){
        var $circ = $(this);
        // store intial start point
        $circ.data('top', $circ.position().top);
        // increment delay for drop
        $circ.delay(i*1000).animate({top:top}, function(){
            // increment delay to return
            $circ.delay( (i+numCircles) * 1000).animate({top:$circ.data('top')});
        });            
    });           
});

DEMO

Upvotes: 2

Anthony Bobsin
Anthony Bobsin

Reputation: 168

I think you are looking for setTimeout(function(){}, milliseconds).

You can learn more about it here.

Upvotes: 0

Related Questions