Reputation: 1216
I am trying to get the position of an html element by nodeName and nodeIndex. I currently use this by passing the nodename and index from the database however...(see below)
$thing = $("BUTTON").eq(1);
thisLeft = $thing.offset().left;
thisTop = $thing.offset().top;
x_left = thisLeft + x_coord
y_top = thisTop + y_coord
I would like to use the following function which works onclick when I pass the object because of its accuracy to get the position even if its in parent elements. Is it possible to pass in the nodename and nodeindex (which I have in a database) like my example of $("BUTTON").eq(1) to return the accurate x and y from the following function...
function findPos(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 };
}
return undefined;
}
This function from the click handler outputs the correct x and y...
var pos = findPos(e);
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
var coordinateDisplay = "x=" + x + ", y=" + y;
console.log(coordinateDisplay);
Upvotes: 1
Views: 54
Reputation: 3218
Html 5 allows a data tag attribute which you can read about with JQuery here.
When you generate the nodes from your database you can do something like
<div class="node" data-nodeName="ImANode" data-nodeIndex="0" ></div>
Then you can select each one with
$("div[data-nodeName='ImANode'][data-nodeIndex='0']")
Upvotes: 1