LearnFast.Ninja

jQuery absolute position of an element

The jQuery function who used to get the absolute position of an element called offset, its returned an element with the top and left variables. The main idea: $("#" + Id).offset();

Step 1: create custom element within element

<div style="padding: 20px;">

    <div id="My_Div" onclick="get_position_by_id('My_Div');" style="position: relative; top: 30px;">

        Click to get my absoulte position

    </div>

</div>


Step 2: create javascript function, call it get_position_by_id

function get_position_by_id(Id) {

    var elem_absoulte_position = $("#" + Id).offset();

    alert("top:" + elem_absoulte_position.top + " , " + "left:" + elem_absoulte_position.left);

}


The main idea:

$("#" + Id).offset();


Complete code:

<html>

<head>

    <title>jQuery absolute position</title>

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

    <script type="text/javascript">

        function get_position_by_id(Id) {

            var elem_absoulte_position = $("#" + Id).offset();

            alert("top:" + elem_absoulte_position.top + " , " + "left:" + elem_absoulte_position.left);

        }

    </script>

</head>

<body>

    <div style="padding: 20px;">

        <div id="My_Div" onclick="get_position_by_id('My_Div');" style="position: relative; top: 30px;">

            Click to get my absoulte position

        </div>

    </div>

</body>

</html>

 

Result:


Tags

jquery

position absolute