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?
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:
CSS:
HTML: