Skip to content

Instantly share code, notes, and snippets.

@osartun
Last active April 16, 2018 22:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save osartun/4154204 to your computer and use it in GitHub Desktop.
Save osartun/4154204 to your computer and use it in GitHub Desktop.
Get a jQuery-set of all the visible elements from one Point in your document. The elements are in reversed order (the element on the top is the last element in the set).
(function ($, document, undefined) {
$.extend({
/**
* A static jQuery-method.
* @param {number} x The x-coordinate of the Point.
* @param {number} y The y-coordinate of the Point.
* @param {Element} until (optional) The element at which traversing should stop. Default is document.body
* @return {jQuery} A set of all elements visible at the given point.
*/
elementsFromPoint: function(x,y, until) {
until || (until = document.body); // Stop traversing here
if (until instanceof $) until = until[0];
var elements = [], previousDisplay = [], current, i, d, computedStyle = window.getComputedStyle;
while ( (current = document.elementFromPoint(x,y)) && current != null && current !== until) {
elements.push(current);
previousDisplay.push(computedStyle ? computedStyle(current)["display"] : current.currentStyle.display);
current.style.display = "none"; // Add display: none, to get to the underlying element
}
i = previousDisplay.length;
while ((d = previousDisplay.pop()) != null && i--) {
elements.get(i).style.display = d; // Restore the previous display-value
}
return $(elements);
}
});
})(jQuery, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment