Getting margin-top of element whilst being animated

125 Views Asked by At

I am animating an element with the top margin. However, when said element reaches a certain margin, I want to create another event. I did what I assumed would work, but it doesnt seem to be doing anything.

So I have an element moving to margin top 300px, and when it hits 300px I want it to got to margin-top -80px.

function raindrop(element,speed) {
    $(element).animate({
        'margin-top':'300px'
    }, speed, 'linear');
    margin = parseInt($(element).css('marginTop'));
    if(margin>=300) {
        $(element).css('marginTop','-80px');
            $(element).animate({
        'margin-top':'300px'
    }, speed, 'linear');
    }
}

I also want to use a re-cursive function here so it keeps doing it. Any ideas what I am doing wrong?

1

There are 1 best solutions below

0
On

You don't need any if statement in your code to check the condition because if statement executes before the animation completes. Instead of if, better to use a callback function which will only execute after the first animation finishes. In callback, you can move your element back to margin-top:-80px once it reaches at 300px. If you also want to do recursion then you can call your raindrop() function as a callback function of second animation which does infinite looping. Here is the modified code:

jQuery:

$(document).ready(function () {
    $("#btn").click(function () {
        raindrop("#mydiv", 1000);
    });
});

function raindrop(element, speed) {
    $(element).animate({
        'margin-top': '300px'
    }, speed, 'linear', function () {
        margin = parseInt($(element).css('marginTop'));
        //alert(margin);
        $(element).animate({
            'margin-top': '-80px'
        }, speed, 'linear', raindrop(element, speed));
    });
}

CSS:

#mydiv
{
    border:1px solid red;
    width:300px;
    height:150px;
}

HTML:

<input type="button" id="btn" value="Press">
<div id="mydiv"></div>