//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:


Example code

The above code was created with:

<!doctype html>
<html lang="en">
        <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
            #imgID {
                width: 100px;
            Current position of <code>#imgID</code>:
        <button id="displayTopButtonID">
            Show number of pixels from the top of the window
        <button id="displayLeftButtonID">
            Show number of pixels from the left of the window
            // pop up the number of pixels from the TOP
            var displayTopPosition = function () {
                console.log('in displayTopPosition...');
            // pop up the number of pixels from the LEFT
            var displayLeftPosition = function () {
                console.log('in displayLeftPosition...');
            //INPUT: trigger displayTopPosition when #displayTopButtonID is clicked
            document.getElementById('displayTopButtonID').onclick   = displayTopPosition;
            //INPUT: trigger displayLeftPosition when #displayLeftButtonID is clicked
            document.getElementById('displayLeftButtonID').onclick  = displayLeftPosition;

Learn more