In this article I will explain how to get the absolute position or screen coordinates of a control using JavaScript. The JavaScript function below calculates the absolute position or screen coordinates of a control. Using this function we can determine the absolute position of a HTML control on X and Y axis.
<script type="text/javascript">
    function GetScreenCordinates(obj) {
        var p = {};
        p.x = obj.offsetLeft;
        p.y = obj.offsetTop;
        while (obj.offsetParent) {
            p.x = p.x + obj.offsetParent.offsetLeft;
            p.y = p.y + obj.offsetParent.offsetTop;
            if (obj == document.getElementsByTagName("body")[0]) {
                break;
            }
            else {
                obj = obj.offsetParent;
            }
        }
        return p;
    }
</script>
 
The above JavaScript function accepts the reference of the HTML object as parameter and then calculates its absolute position. In order to explain how it works I have created a small sample
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script type = "text/javascript">
        function GetTextboxCordinates() {
            var txt = document.getElementById("txtText");
            var p = GetScreenCordinates(txt);
            alert("X:" + p.x + " Y:" + p.y);
        }
    </script>
</head>
<body>
    <form id="form1"
    <input id = "txtText" type = "text" />
    <input value = "Get Coordinates" type = "button" onclick="GetTextboxCordinates()" />
    </form>
</body>
</html>
 

In the above example, I have a HTML Textbox and a Button and onclick of Button I am displaying the co-ordinates of the control in a JavaScript alert

Get Absolute position of HTML control using Javascript
 
Browser Compatibility

The above code has been tested in the following browsers.
Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
With this we come to an end this article you can download the sample source code using the download link given below.