views:

750

answers:

5

I have the coordinates (X,Y) of a point in an HTML document. How do I determine what DOM node is at those coordinates?

Some ideas:

  • Is there a DOM hit test function that I missed, that takes a point (X,Y) and returns the DOM element there?
  • Is there an efficient way to walk the DOM element tree to find the containing element? This seems like it would be tricky because of absolutely positioned elements.
  • Is there a way to simulate an event at a given (X,Y) position such that the browser ends up creating an event object that has a pointer to the element?

(Background: I'm embedding Qt's QWebView in a native application. I'm trying to vary the context menu that the Qt widget provides based on the DOM node that the mouse is over, but Qt 4.5 cannot hit test to a DOM element, though that functionality is coming in 4.6. So I'm hoping I can toss the the coordinate into Javascript and do the hit testing there with DOM APIs.)

Thanks!

+6  A: 

If IE and FF3+ happen to be your target audiences, then you're in luck: use document.elementFromPoint(x, y) (MSDN ref, Mozilla ref):

Returns the element from the document ... which is the topmost element which lies under the given point.

If you need to support other browsers, I can't think of many options other than what you suggest (traverse the entire DOM, looking at element positions and sizes and seeing if any of them encapsulate your (x, y)).

I don't think the event simulation will work but it is an interesting idea. My understanding of event dispatching is you specify the target that the event is for, which is precisely what you are trying to find out in the first place.

Crescent Fresh
Perfect! elementFromPoint works in WebKit, which is what I'm embedding.. Flawless victory!
Geoff
+1  A: 

In IE exist document.body.componentFromPoint(x,y). I don't know if there is a cross browser implementation.

Rodrigo
componentFromPoint doesn't return the node.
Murali VP
+1  A: 

This is probably not the best solution, but you can traverse the dom tree starting with finding co-ordinates of ancestor nodes that contains your x and y positions and quickly get to the leaf node that contains your co-ordinates. For getting the positions of a node in a cross browser way you can look at the JS toolkits. One that I have used is dojo. Take a look at dojo._getMarginBox here

Murali VP
+1  A: 
document.elementFromPoint(x,y)

Documented here for Firefox 3 and here for IE, but see quirksmode for cross-browser differences.

wdebeaum
A: 

You can use jQuery for that. I'd bind all needed dom elements to the click event, this will give me appropriate dom object on click as well as mouse position.

petrpetrov