Skip to content Skip to sidebar Skip to footer

Getting DIV Id Based On X & Y Position

The problem I'm trying to solve is 'What's at this position?' It's fairly trivial to get the x/y position (offset) of a DIV, but what about the reverse? How do I get the id of a DI

Solution 1:

Unfortunately, triggering a manufactured/simulated mouse event won't work, since when you dispatch it, you have to provide a target element. Since that element is the one you're trying to figure out, all you could do is dispatch it on the body, as if it had already bubbled.

You really are left to do it on your own, that is manually walk through the elements you're interested in, and compare their position/size/zIndex to your x/y point and see if they overlap. Except in IE and more recently FF3, where you can use

var el = document.elementFromPoint(x, y);

See

http://developer.mozilla.org/En/DOM:document.elementFromPoint

http://msdn.microsoft.com/en-us/library/ms536417(VS.85).aspx


Solution 2:

function getDivByXY(x,y) {
   var alldivs = document.getElementsByTagName('div');

   for(var d = 0; d < alldivs.length; d++) {
      if((alldivs[d].offsetLeft == x) && (alldivs[d].offsetTop == y)) {
         return alldivs[d];
      }
   }

   return false;
}

Solution 3:

Use a JQuery selector to filter the list of all DIVs for one that matches your position criteria?


Solution 4:

Create a mouse event listener, then trigger a mouse event at that location. This should give you the entire stack of elements at that location.

Or, look at the source of Firebug.


Solution 5:

One option is to build an array of "div-dimension" objects. (Not to be confused with the divs themselves... IE7 perf is frustrating when you read dimensions off of object.)

These objects consist of a pointer to the div, their dimensions (four points... say top, left, bottom, and right), and possibly a dirty bit. (Dirty bit is only really needed if the sizes change.

You could then iterate through the array and check dimensions. It requires O(n) to do that on each mouse move. You might be able to do slightly better with a binary search style approach... maybe.

If you do a binary search style approach, one way is to store 4 arrays. Each with a single point of the dimension, and then binary search on all four. O(4logn) = O(logn).

I'm not saying I recommend any of these, but they MIGHT work.


Post a Comment for "Getting DIV Id Based On X & Y Position"