In this article I will explain with an example, how to get the absolute position or screen coordinates of a control using JavaScript.
 
 

HTML Markup

The following HTML Markup consists of:
TextBox – To be used for providing co-ordinates.
Button – For displaying co-ordinates of control i.e. TextBox.
The Button has been assigned with JavaScript onclick event handler.
<input id="txtText" type="text" />
<input value="Get Coordinates" type="button" onclick="GetTextboxCordinates()" /> 
 
 

Getting Absolute Position using JavaScript

When the Button is clicked, the GetTextboxCordinates JavaScript function gets called.

GetTextboxCordinates

Inside the GetTextboxCordinates function, TextBox Id is fetched and passed as parameter to GetScreenCoordinates function.
GetScreenCoordinates
Inside the GetScreenCoordinates function, the calculation is performed on absolute position or screen co-ordinates of a control, then WHILE Loop is executed.
Inside the WHILE Loop, the checked is performed if the condition is TRUE loop will break, if FALSE object will set.
The GetScreenCoordinates function is used to determine the absolute position of a HTML control on X and Y axis.
<script type="text/javascript">
    function GetScreenCoordinates(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;
    }
 
    function GetTextboxCordinates() {
        var txt = document.getElementById("txtText");
        var p = GetScreenCoordinates(txt);
        alert("X:" + p.x + " Y:" + p.y);
    }
</script>
 
 

Screenshot

Get Absolute Position (Screen Coordinates) of HTML Control using JavaScript
 
 

Browser Compatibility

The above code has been tested in the following browsers.
Microsoft Edge   FireFox  Chrome  Safari  Opera
* All browser logos displayed above are property of their respective owners.
 
 

Demo

 
 

Downloads