Search code examples
javascriptobjectoffset

Javascript - object.offsetTop and .offsetLeft gives 0


I'm trying to get the position of an element by using Javascript. I have used clientTop, offsetHeight, window.getComputedStyle(box1).top and a few things in between but all I get when I console log it is 0. The element is placed almost in the middle of the page so it should be all but 0 in the result.

HTML:

<body>
    <h1>Box placement</h1>

    <div id='box1' class='box center green size200'>

    </div>
</body>

JS:

let box1 = document.querySelector('#box1');

let browserHeight = window.innerHeight;
let browserWidth = window.innerWidth;
let boxHeight = box1.clientTop;
let boxWidth = box1.offsetLeft;

function printInfo() {                               //Result
    console.log(browserHeight);                      //1185
    console.log(browserWidth);                       //1266
    console.log(boxHeight);                          //0
    console.log(boxWidth);                           //0
    console.log(window.getComputedStyle(box1).top);  //auto
    console.log(box1.offsetLeft);                    //0
}

printInfo();

Any ideas to where I might have gone wrong? Here is a fiddle with the CSS as well: http://jsfiddle.net/1f23v9nj/1/


Solution

  • That behaviour is caused by the less.js library. If you don't really need its features, then don't include it -- problem solved.

    If you do need it -- for reasons not apparent from the code in your question -- then wait for the less.pageLoadFinished promise to resolve, as follows:

    less.pageLoadFinished.then(function () {
        'use strict';
    
        let box1 = document.querySelector('#box1');
        // ... etc
    });
    

    See updated fiddle