Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does document.elementFromPoint return null for elements outside visible document

Why does document.elementFromPoint(500,1000) here return null if that pixel is located outside the visible document when the document loads?

I've noticed document.elementFromPoint returns null for any point that is initially outside the visible document, as well as after it is scrolled into view.

A simple way to test this is in Chrome (ctrl-shift-i -> scripts -> 'watch expressions') (ensure that the page height is narrowed to less than 1000 pixels)

EDIT: so it does make sense, as per docs

  1. always returns null for points outside visible area
  2. x and y are relative to the top left and right of visible screen

I failed on both assumptions,

like image 991
Joel Avatar asked Mar 09 '11 23:03

Joel


1 Answers

So you kinda answered your own question: document.elementFromPoint works in the viewport coordinate rather than document. So all you need to do is to add a scroll compensation.

The following code worked out for me:

document.elementFromPoint(X - window.pageXOffset, Y - window.pageYOffset);

Or if you are listening for an event that would be:

document.elementFromPoint(e.pageX - window.pageXOffset, e.pageY - window.pageYOffset);
like image 191
Anton Bielousov Avatar answered Sep 23 '22 18:09

Anton Bielousov