Given two points on a webpage and a set of DOM elements, how to find out the subset of those DOM elements that sit inside the rectangle area defined by the two points?
I am working on a web-based gallery, in which every photo is wrapped in a li
tag. When a user drag out a rectangle area with mouse, all li
elements inside the rectangle are marked as selected.
Prefer a jQuery solution for less wordy and an efficient way.
The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.
The correct approach is to use element. getBoundingClientRect() : var rect = element. getBoundingClientRect(); console.
AppendChild. The simplest, most well-known method of appending an element to the DOM is certainly the appendChild() .
In the HTML DOM, the Element object represents an HTML element, like P, DIV, A, TABLE, or any other HTML element.
Try something like this:
// x1, y1 would be mouse coordinates onmousedown
// x2, y2 would be mouse coordinates onmouseup
// all coordinates are considered relative to the document
function rectangleSelect(selector, x1, y1, x2, y2) {
var elements = [];
jQuery(selector).each(function() {
var $this = jQuery(this);
var offset = $this.offset();
var x = offset.left;
var y = offset.top;
var w = $this.width();
var h = $this.height();
if (x >= x1
&& y >= y1
&& x + w <= x2
&& y + h <= y2) {
// this element fits inside the selection rectangle
elements.push($this.get(0));
}
});
return elements;
}
// Simple test
// Mark all li elements red if they are children of ul#list
// and if they fall inside the rectangle with coordinates:
// x1=0, y1=0, x2=200, y2=200
var elements = rectangleSelect("ul#list li", 0, 0, 200, 200);
var itm = elements.length;
while(itm--) {
elements[itm].style.color = 'red';
console.log(elements[itm]);
}
For a vanilla JS solution, check out this pen: https://codepen.io/ArtBIT/pen/KOdvjM
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With