Detect overlapping elements

16 views Asked by At

I have a few draggable divs that have the same parent. How would I get an array of divs that are touching anoter specified div?

Eg:

let item1:HTMLDivElement;

let touchingDivs:HTMLDivElement[] = getTouchingDivs(item1);

I've tried something like

var overlap = !(rect1.right < rect2.left ||rect1.left > rect2.right ||rect1.bottom < rect2.top || rect1.top > rect2.bottom)

https://stackoverflow.com/a/12067046/20522485

but it wouldn't work because I do not know which 2 identified elements will be touching with each other

1

There are 1 answers

0
Isabella Rossi On

use function getTouchingDivs(item1). This function compares the sibling divs and rectangles of item1. After this use getBoundingClientRect() function which return array of divs based on their position and sizes which are overlapping with item1. Here is the example:

function getTouchingDivs(item) {
    let touchingDivs = [];
    let itemRect = item.getBoundingClientRect();
    let siblingDivs = item.parentNode.children;

    for (let div of siblingDivs) {
        if (div !== item) {
            let divRect = div.getBoundingClientRect();
            let overlap = !(itemRect.right < divRect.left || itemRect.left > divRect.right || itemRect.bottom < divRect.top || itemRect.top > divRect.bottom);
            if (overlap) {
                touchingDivs.push(div);
            }
        }
    }
    return touchingDivs;
}

let item1 = document.getElementById("yourDivId"); // Replace with your div's ID
let touchingDivs = getTouchingDivs(item1);