//INPUT: Read element positions

<New code>

//INPUT JS: document.getElementById("inputID").offsetTop
— returns the top position of #inputID in relation to its parent element

//INPUT JS: document.getElementById("inputID").offsetLeft
— returns the left position of #inputID in relation to its parent element

Find out where something is

When you want to move something around, you often need to read the current position of something.

In Javascript, if you have an HTML element that has an ID and has been set to position: absolute, you can read the top and left positions of it using the following code:

document.getElementById('exampleID').offsetTop
document.getElementById('exampleID').offsetLeft

Example code


The above code was created with:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>INPUT - Read element positions</title>
        <meta name="description" content="Learn how to read element positions with Javascript">
        <meta name="author" content="Dave Drapak">
        <!--
            Change log:
                26. Sept 2015   - created!
                2. Oct          - simplified and add console logs
                5. March 2017   - reworked for clearer programming style
        -->
        <style>
            #imgID {
                width: 100px;
            }
        </style>
    </head>
    
    <body>
        <h1>
            Current position of <code>#imgID</code>:
            <img 
                id="imgID" 
                src="https://www.kasandbox.org/programming-images/food/sushi.png">
        </h1>
        
        <button id="displayTopButtonID">
            Show number of pixels from the top of the window
        </button>
        
        <button id="displayLeftButtonID">
            Show number of pixels from the left of the window
        </button>
 
        <script>
            // pop up the number of pixels from the TOP
            var displayTopPosition = function () {
                console.log('in displayTopPosition...');
                alert(
                    document.getElementById('imgID').offsetTop
                )
            }
            
            // pop up the number of pixels from the LEFT
            var displayLeftPosition = function () {
                console.log('in displayLeftPosition...');
                alert(
                    document.getElementById('imgID').offsetLeft
                )
            }
            
            //INPUT: trigger displayTopPosition when #displayTopButtonID is clicked
            document.getElementById('displayTopButtonID').onclick   = displayTopPosition;
            
            //INPUT: trigger displayLeftPosition when #displayLeftButtonID is clicked
            document.getElementById('displayLeftButtonID').onclick  = displayLeftPosition;
        </script>
    </body>
</html>

Learn more