How can I animate a div to the same position as another div.
I want to animate the left position of #div1 to the same left position of #div2
When I use .position().left OR .offset().left to get the left position of #div2 then try to animate #div1 to the same position, the animation runs but it moves #div1 to the same position as #div 2 PLUS the original position of #div1 (i.e. they are not aligned).
Here's a simplified version of the script. Hope you can help :)
<script>
$(function({
var end = $(#div2).position().left;
$(#div1).animate({"left": end.left}, "slow");
});
</script>
<html>
<div id="div1"></div>
<div id="div2"></div>
</html>
Well, I guess you were already there. However... the code is depending on your actual layout.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">
body, td, input, button{
font-family: Tahoma,Verdana,Helvetica,Arial,sans-serif !important;
font-size:11px;
}
label{
width:100px;
display: inline-blocK;
}
#div1{
width:100px;
height:50px;
background-color:red;
position:absolute;
top:100px;
left:30px;
}
#div2{
width:80px;
height:30px;
background-color:green;
position:absolute;
top:200px;
left:100px;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#moveitButton").click(function() {
doit();
})
});
function doit() {
var div2Pos = $("#div2").position();
var div2Width = $("#div2").css("width");
var div2Height = $("#div2").css("height");
$("#div1").animate({left:div2Pos.left, width:div2Width, height:div2Height}, 1000);
}
</script>
</head>
<body>
<div id="div1">div #1</div>
<div id="div2">div #2</div>
<button id="moveitButton">move it!</button>
</body>
</html>
(At least this works in my browser)
kr, zara
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With