javascript tutorial - [Solved-5 Solutions] Retrieve the position (X,Y) of an HTML element - javascript - java script - javascript array



Problem:

How to retrieve the position (X,Y) of an HTML element ?

Solution 1:

The correct approach is to use element.getBoundingClientRect():

var rect = element.getBoundingClientRect();
console.log(rect.top, rect.right, rect.bottom, rect.left);
click below button to copy the code. By JavaScript tutorial team

Solution 2:

function getOffset( el ) {
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}
var x = getOffset( document.getElementById('yourElId') ).left; 
click below button to copy the code. By JavaScript tutorial team

Solution 3:

function getOffset(el) {
  el = el.getBoundingClientRect();
  return {
    left: el.left + window.scrollX,
    top: el.top + window.scrollY
  }
}
click below button to copy the code. By JavaScript tutorial team

Using this we can call

getOffset(element).left
click below button to copy the code. By JavaScript tutorial team

or

getOffset(element).top
click below button to copy the code. By JavaScript tutorial team

Solution 4:

var getAbsPosition = function(el){
    var el2 = el;
    var curtop = 0;
    var curleft = 0;
    if (document.getElementById || document.all) {
        do  {
            curleft += el.offsetLeft-el.scrollLeft;
            curtop += el.offsetTop-el.scrollTop;
            el = el.offsetParent;
            el2 = el2.parentNode;
            while (el2 != el) {
                curleft -= el2.scrollLeft;
                curtop -= el2.scrollTop;
                el2 = el2.parentNode;
            }
        } while (el.offsetParent);

    } else if (document.layers) {
        curtop += el.y;
        curleft += el.x;
    }
    return [curtop, curleft];
};
click below button to copy the code. By JavaScript tutorial team

Solution 5:

Object.defineProperty( Element.prototype, 'documentOffsetTop', {
    get: function () { 
        return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 );
    }
} );

Object.defineProperty( Element.prototype, 'documentOffsetLeft', {
    get: function () { 
        return this.offsetLeft + ( this.offsetParent ? this.offsetParent.documentOffsetLeft : 0 );
    }
} );
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Retrieve the position (X,Y) of an HTML element