Search code examples
javascripthtmldhtml

HTML, JS: positioning an element is inaccurate


my aim is to put a dropdown list into a cell.

var obj = document.getElementById('dropdown');
var coords = { x: 0, y: 0 };
var element = this;
while (element)
{
 coords.x += element.offsetLeft;
 coords.y += element.offsetTop;
 element = element.offsetParent;
}
obj.style.left = coords.x+'px';
obj.style.top = coords.y+'px';

however, this cant find the accurate position. How to fix it?


Solution

  • This approach should work perfectly, maybe something else is messing up the positioning?

    If you have an element with style position: relative, elements that are added to that element with style position: absolute with still be relative to that element. If you try to determine the position of an element just by looking at the offset and then walking upwards (disregarding any relatively positioned elements) you wont get the right values. You should find the closest common element with relative positioning and get the offset up to that element.