LearnFast.Ninja

jQuery move div to another div

Write Div1 and Div2 at div 1 write position: relative and z-index: 1. Write an animate jQuery and use the left position of Div1 for the property. To see how it works copy the working example code.

Step 1: Write Div1 and Div2 at div 1 write position: relative and z-index: 1. 

<div id="Div1" style="position: relative; display: inline; width: 200px; background-color: Orange; z-index: 1;">

    I am Div1

</div>

<div id="Div2" style="display: inline; width: 200px; background-color: Yellow;">

    I am Div2

</div>

 
Step 2: Write an animate jQuery and use the left position of Div1 for the property. 

var Div2_Position = $("#Div2").position();

$("#Div1").animate({ "left": Div2_Position.left - 10 }, 900);

 
Working example code: 

<html>

<title>jQuery</title>

<head>

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.js"></script>

    <script type="text/javascript">

        function Main() {

            var Div2_Position = $("#Div2").position();

            $("#Div1").animate({ "left": Div2_Position.left - 10 }, 900);

        }

    </script>

</head>

<body>

    <div id="Div1" style="position: relative; display: inline; width: 200px; background-color: Orange; z-index: 1;">

        I am Div1

    </div>

    <div id="Div2" style="display: inline; width: 200px; background-color: Yellow;">

        I am Div2

    </div>

    <br />

    <br />

    <input type="button" value="Move Div1 to Div2" onclick="Main();" />

</body>

</html>

 
Result: 


Tags

jquery

jquery-animate