Skip to content Skip to sidebar Skip to footer

Element Coordinates In Pure Javascript

Say that I have an element inside a div (or any other containing element, or perhaps just in the body of the document). How do I get the (x,y) coordinates of that element, relative

Solution 1:

The offsetTop and offsetLeft properties are relative to offsetParent so you can get an element's position relative to its parent for free. If you want the position relative to the entire body then you need to traverse the offsetParent chain and sum the values.

The following function accomplishes this:

functionfindPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    returnundefined;
}

Solution 2:

Use the below

document.getElementById("elementId").offsetTop;
document.getElementById("elementId").offsetLeft;

Solution 3:

Going off of ShankarSangoli's post, it can be expanded this way. Get the difference between the parent (container) and the child (element in question):

var parentOffsetTop = document.getElementById("parentId").offsetTop;
var parentOffsetLeft = document.getElementById("parentId").offsetLeft;
var childOffsetTop = document.getElementById("childId").offsetTop;
var childOffsetLeft = document.getElementById("childId").offsetLeft;

var xOffset = parentOffsetLeft - childOffsetLeft;
var yOffset = parentOffsetTop - childOffsetTop;

EDIT: seems I was mistaken, offsetLeft and offsetTop are based off of the parent anyway. You do not need to do this manually!

Post a Comment for "Element Coordinates In Pure Javascript"