views:

393

answers:

1

I am building an app where I repeatedly need to get lists of html elements sitting under a specific location (x,y relative to the viewport, e.g.). I am considering the following approaches, but none are satisfying:

(1) Go through the html, build a data-structure that keeps track of the x,y position of every element (x,y -> set of elements), and then access this data-structure when I need to do a lookup. Unfortunately, this approach is a bit cumbersome and I am looking for a better way to solve this problem. Plus, I fear it may be way too slow.

(2) A probably better approach I am considering is to temporarily add a top-level event handler that captures all hover events, to fake a mouse-hover at the particular position, and then to remove the handler, but it looks like this will only return the top-most element (e.g., if there are a bunch of absolute-position divs over a particular location, I think it will only return the one with the highest z-index, whereas I need all, although I am not sure).

(3) For IE, there is componentFromPoint(x, y), but I can't find an equivalent in other browser -- that and it only returns the top-most element.

Note that the app is built as a bookmarklet and I have no control over the underlying html -- this unfortunately curtails any easy server-side solutions.

I am willing to use libraries (currently on jquery).

FYI, so far the best I have found here is http://stackoverflow.com/questions/48999/getting-div-id-based-on-x-y-position; wondering if there is something more up-to-date.

+1  A: 

You might be looking for the elementFromPoint method that exists in MSIE, FF3+ and in some form in Safari and Opera. It may be also worth taking a look at getBoundingClientRect. Combine the two and you should be in business.

You might also be able to speed up approach #1 by keeping the calculated structure between lookups and only recalculate it when changes actually occur on the page. Take a look at how selector engines (Sizzle in paticular) cache their lookups and expires the cache when the DOM changes.

It may seem contrived, but calculating every element's position is what drag-and-drop handlers have been doing up until now. There are a dozen free ones out there that have this stuff properly optimized (my hunch is that YUI's will have the most readable code). These may be dated though or trying to support browsers that you don't want/need to.

Borgar
Thanks. elementFromPoint and componentFromPoint are what I have been looking at. Not great, but might just have to do with. Good advice on looking at YUI's implementation of drag-and-drop.
George Greze