LearnFast.Ninja

jQuery get div position – left and top

Define a new variable and get div position relative to the offset parent. Use offset to get current position relative to the document. Get left or top attributes. To test how to do it copy the Working example code.

Step 1: Define a new variable and get div position relative to the offset parent. 
var Div2_Position = $("#Div2").position();
 
Step 2: Use offset to get current position relative to the document. 

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

 
Step 3: Get left or top attributes. 

alert("Div2_Position.left: " + Div2_Position.left + "\nDiv2_Position.top: " + Div2_Position.top);

 
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();

            alert("Div2_Position.left: " + Div2_Position.left + "\nDiv2_Position.top: " +

           Div2_Position.top);

        }

    </script>

</head>

<body>

    <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

position offset