Document.elementFromPoint

By  on  

Reacting to events with JavaScript is the foundation of a dynamic experiences on the web. Whether it's a click event or another typical action, responding to that action is important. We started with assigning events to specific elements, then moved to event delegation for efficiency, but did you know you can identify elements by position on the page? Let's look at document.elementFromPoint and document.elementsFromPoint.

The document.elementFromPoint method accepts x and y parameters to identify the top-most element at a point:

const element = document.elementFromPoint(100, 100);
// 

If you want to know the entire element stack, you can use document.elementsFromPoint:

const elements = document.elementsFromPoint(100, 100);
// [
, , ]

The elementFromPoint and elementsFromPoint are really helpful for experiences where developers don't want to assign individual events. Games and entertainment sites could benefit from these functions. How would you use them?

Recent Features

Incredible Demos

  • By
    Create Twitter-Style Dropdowns Using jQuery

    Twitter does some great stuff with JavaScript. What I really appreciate about what they do is that there aren't any epic JS functionalities -- they're all simple touches. One of those simple touches is the "Login" dropdown on their homepage. I've taken...

  • By
    MooTools 1.2 Tooltips: Customize Your Tips

    I've never met a person that is "ehhhh" about XHTML/javascript tooltips; people seem to love them or hate them. I'm on the love side of things. Tooltips give you a bit more information about something than just the element itself (usually...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!