Skip to content Skip to sidebar Skip to footer

How Do I Grab The OffsetX Of The Parent Div?

Been struggling for a while on this so I decided to craft up a jsfiddle to show an example: gameworld = document.getElementById('GameWorld'); character = document.getElementById(

Solution 1:

You can add the child’s offsetLeft and offsetTop properties. For arbitrary depths (it seemed cleaner):

var offsetX = e.offsetX;
var offsetY = e.offsetY;

var element = e.target;

while (element !== gameworld) {
    offsetX += element.offsetLeft;
    offsetY += element.offsetTop;
    element = element.parentNode;
}

character.style.left = offsetX + 'px';
character.style.top = offsetY + 'px';

Updated fiddle


Solution 2:

Note that if this is still buggy, you can substract target.offsetWidth/2 or target.offsetHeight/2 depending on the context. (because offsetLeft is calculated from the center of the current element.)


Post a Comment for "How Do I Grab The OffsetX Of The Parent Div?"