Sometimes, we want to animate margin top CSS property with jQuery.
In this article, we’ll look at how to animate margin top CSS property with jQuery.
Animate the Margin Top CSS Property with jQuery
To animate margin top CSS property with jQuery, we can call the animate
method on the selected elements
For instance, we write:
<div class='item'>
<div class='info'>
item info
</div>
</div>
to add the div we want to animate the margin-top property for.
Then we write:
$(".item").mouseover(() => {
$('.info').animate({
marginTop: '-50px',
opacity: 0.5
}, 1000);
});
to call mouseover
on the outer div with a callback that does the animation on the inner div.
To do the animation on the inner div, we select the inner div and then call animate
on it.
We call animate
with an object that sets the marginTop
to '-50px'
to move the inner div 50px up.
Also, we set the opacity
to 0.5 to reduce the opacity of the inner div.
And the animation runs for 1 second as specified by the 2nd argument of animate
.
Now when we put our mouse over the divs, we should see the text move up.
Conclusion
To animate margin top CSS property with jQuery, we can call the animate
method on the selected elements