I have a parent-child structure of div elements (parent is the div called dartboard, a child div called rotatingDiv and that then has a child called crosshair).
The dartboard container holds a rotating container (rotaingDiv), which then holds a child element (crosshair). I would like to find the x and y positions in relation to the dartboard container. Here is what I have at present:
$('#dartboard').append( $('#rotatingDiv').append( $('#crosshair') ) );
X = $('#crosshair').position().left.toFixed(1)
Y = $('#crosshair').position().top.toFixed(1)
console.log("x is "+X+", y is "+Y);
This process runs within a per-second timer, upon inspection of the x and y values, I've noticed that i'm only receiving this information in relation of the crosshair element being inside the rotatingDiv instead of being at the dartboard level (parent of parent). Does anyone know how I can do this?
This should work:
var pos1 = $("#crosshair").position(); var pos2 = $("#crosshair").parent().position(); // or $('#rotatingDiv').position(); var x = (pos1.left + pos2.left ).toFixed(1); var y = (pos1.top + pos2.top ).toFixed(1);
Note: jQuery does not support getting the position coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.
You can check the API here.
var parentLeft = $('#parent').offset().left, parentTop = $('#parent').offset().top childLeft = $('#child').offset().left, childTop = $('#child').offset().top; // Positions respective to parent var top = parentTop - childTop, left = parentLeft - childLeft;
You can also use