Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DOM elements inside a rectangle area of a page

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.

like image 987
powerboy Avatar asked Oct 23 '10 01:10

powerboy


People also ask

How do I grab an element from a DOM?

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.

How do you find the position of an element in a page?

The correct approach is to use element. getBoundingClientRect() : var rect = element. getBoundingClientRect(); console.

Which method is used to add components or elements to the DOM?

AppendChild. The simplest, most well-known method of appending an element to the DOM is certainly the appendChild() .

What is element in DOM?

In the HTML DOM, the Element object represents an HTML element, like P, DIV, A, TABLE, or any other HTML element.


1 Answers

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

like image 78
ArtBIT Avatar answered Oct 15 '22 06:10

ArtBIT