Jquery animates a div in the same position as another div

How can I animate a div at the same position as another div.

I want to animate the left position # div1 in the same left position # div2

When I use .position (). left OR.offset (). left, to get the left position # div2, try animating # div1 to the same position, the animation starts, but it moves # div1 to the same position as #div 2 PLUS starting position # 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>
+5
source share
1 answer

Well, I think you were already there. However ... the code depends on your actual location.

<!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>

( , )

kr, zara

+4

All Articles