Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery animate div to same position as another div

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>
like image 610
user469453 Avatar asked Oct 13 '22 19:10

user469453


1 Answers

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

like image 179
user533812 Avatar answered Oct 18 '22 03:10

user533812