Tuesday, January 15, 2013

Find the child element position inside the parent element using Jquery/Java Script

In this post I will explain how to find the child element position inside the parent element using jquery/java script.

Let's start, I have two div elements one is parent div and other is child div and a label to show the output.

<div id="Parentdiv">
   <div id="Childdiv">          
       SAMPLE TEXT<br/>SAMPLE TEXT<br/>SAMPLE TEXT<br/>
       SAMPLE TEXT<br/>SAMPLE TEXT<br/>SAMPLE TEXT<br/>
       SAMPLE TEXT<br/>SAMPLE TEXT<br/>SAMPLE TEXT<br/>
       SAMPLE TEXT<br/>SAMPLE TEXT<br/>SAMPLE TEXT<br/>
       SAMPLE TEXT<br/>SAMPLE TEXT<br/>SAMPLE TEXT<br/>
       SAMPLE TEXT<br/>SAMPLE TEXT<br/>SAMPLE TEXT<br/>           
    </div>
 </div>
<br />
<label id="lblPosition" style="font-weight:bold"></label>

The css for these divs are as following:
<style type="text/css">
        #Parentdiv
        {
            height:200px;
            width:150px;
            border:1px solid black;
            overflow:auto;
            padding:5px;
        }
        #Childdiv
        {
            border:1px solid red;
        }
 </style>

Now I will get the position of div ("Childdiv") with respect to div("Parentdiv") using jquery.
<script type="text/javascript">
        //Call the GetInnerElementPosition function to get the child div position inside
        //parent div on page load
        window.onload = GetInnerElementPosition;
        //Function to get the child div poition inside parent div
        function GetInnerElementPosition() {      
            var parentElement = $("#Parentdiv");
            var childElement = $("#Childdiv");
            var positionX, positionY;
            //find the top position of child div
            positionY = childElement.offset().top - parentElement.offset().top;
            //find the left position of child div
            positionX = childElement.offset().left - parentElement.offset().left;
            //display the child div positon
            document.getElementById("lblPosition").innerHTML = "Child div position co-ordinates are: X=" + positionX + " and Y=" + positionY;
        }
</script>
In the above function GetInnerElementPosition I have used the .offset() method of jquery to get the position of parent div and child div on page. The .offset() method allows us to retrieve the current position of an element relative to the document.

Following code line will give the top position of child div relative to parent div.
//find the top position of child div
positionY = childElement.offset().top - parentElement.offset().top;
Following code line will give the left position of child div relative to parent div.
//find the left position of child div
positionX = childElement.offset().left - parentElement.offset().left;

Below is the sample output:

No comments:

Post a Comment

^ Scroll to Top