While I was animating two boxes with jQuery at same pace with setting marginTop, the second box will move faster than the first box.
<div id="box1" style="width:500px;height:80px;background-color:blue;">box 1</div>
<div id="box2" style="width:500px;height:80px;background-color:green;margin-left:510px;">box 2</div>
<script type="text/javascript">
jQuery("#box1").animate({marginTop:"-=80px"}, {duration: 1500});
jQuery("#box2").animate({marginTop:"-=80px"}, {duration: 1500});
</script>
However, when I apply the same setting Top, both box move at same pace.
<div id="box1" style="width:500px;height:80px;background-color:blue;position:relative;">box 1</div>
<div id="box2" style="width:500px;height:80px;background-color:green;margin-left:510px;position:relative;">box 2</div>
<script type="text/javascript">
jQuery("#box1").animate({top:"-=80px"}, {duration: 1500});
jQuery("#box2").animate({top:"-=80px"}, {duration: 1500});
</script>
Any idea why this happening this way?
You can see the effect more clearly in this fiddle
The reason why it is happening is because your second
divis below the firstdiv. And themarginproperty is relative to the elements surrounding it. The top div will move slower because the element that is above (in this case thebody) is not moving. But your div on the bottom has to move faster in order to maintain thatmarginproperty relative to the element above it. In other words, it wants to MAINTAIN that property once the animation is finished.In my fiddle, each
divstarts withmargin-top: 100px. Now when they are animated, they want tomarginTop: "-=80px", which means that they need to end up atmargin-top: 20px. In the top elements case, it only needs to move 80px upward, becausebodyisn’t moving. But the bottomdivneeds to move 80px PLUS the amount that the topdivmoved, which is another 80px, for a total of 160px. Thedivneeds to move 2x the amount of pixels in the same amount of time, so it will move faster.We can further illustrate that the
marginproperty is a relative property from this fiddle. Even though I’m only animating the topdiv, the bottomdivis moving too because it needs to keep thatmarginvalue consistent.The reason why your second piece of code allows the
divs to move at the same speed is because thetopproperty is not a relative property of any element besides it’s container (the right container that is, probable that it’s not it’s direct container), so they will both move at the same speed.Not sure if this is clear.