Advanced Hit Testing APIs

msElementsFromPoint() and msElementsFromRect()

This demo uses new hit testing APIs to build tools that can select elements underneath other elements or all the elements that intersect a rectangle.

Your browser doesn't support the advanced hit testing APIs elementsFromRect() and elementsFromPoint().
You'll need a browser that supports these features, such as Internet Explorer 10, to play this game.

Try it out! The scrapbook page designer below uses new hit testing APIs to provide advanced selection tools. Using the Click Select tool, you can click on an element to select it. While holding the mouse button down, you can scroll the mouse wheel to select items underneath other items. Using the Drag Select tool, you can drag to create a selection rectangle that selects all the items intersecting that rectangle. In browsers that don't support these APIs, you'll only be able to use the Click Select tool and it will only select the top-most element.

Hit Test Results

Scrapbook Editor

Outdoor Seattle

Using the Hit Testing APIs

Until now, browsers exposed only a single hit testing API, called elementFromPoint(x,y). Given a point, the method returns the top-most element under that point. However, it doesn't allow you to find elements underneath other elements.

New hit test APIs in IE10 not only allow you to determine all the elements under a certain point, but also all the elements intersecting a rectangle. On the left, you'll see the results being returned by these APIs as you use the demo.

To find all of the elements under a given point, use msElementsFromPoint(x, y). To find all of the elements which intersect a rectangle, use msElementsFromRect(top, left, width, height).

var nodeList = document.msElementsFromRect(x,y,width,height)
var nodeList = document.msElementsFromPoint(x,y)

The returned nodeList is sorted by z-index so that you can tell the relative stacking order of the elements.

Best Practice!

Always use feature detection. When using msElementsFromPoint, it is often a good idea to use elementFromPoint(x, y) as a fallback for other browsers:

var hitTestResults;
if(document.msElementsFromPoint) {
	hitTestResults = document.msElementsFromPoint(x,y);
}else if(document.elementFromPoint) {
	hitTestResults = [document.elementFromPoint(x,y)];
	hitTestResults = [];

In the demo above, the Click Select tool falls back to elementFromPoint(x, y) in browsers that do not support these new APIs. So in the demo, you'll be able to select top-most items, but you won't be able to scroll the mouse wheel to select items underneath.