Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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=200var 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

Post a Comment for "Get Dom Elements Inside A Rectangle Area Of A Page"