MAC
MAC

Reputation: 67

How to know a div is fully contain to another

How to identify a one div is fully contain to another ? i have 2 div say A and B . i need to know the A is fully contained inside the B when i dragged to A, and no overlap with A

Upvotes: 0

Views: 77

Answers (2)

eisbehr
eisbehr

Reputation: 12452

Use could use IntersectionObserver for this task.

let options = {
  root: document.querySelector('#container'),
  rootMargin: '0px',
};

let callback = entries => {
  entries.forEach(entry => {
    if (entry.intersectionRatio >= 1) {
      console.log("#" + entry.target.id + " is fully inside #container");
    }
    else {
      console.log("#" + entry.target.id + " is NOT fully inside #container");
    }
  });
};

let observer = new IntersectionObserver(callback, options);
observer.observe(document.querySelector('#inner'));
observer.observe(document.querySelector('#outer'));
#container {
  width: 100px;
  height: 100px;
  background: blue;
  position: relative;
}

#inner, #outer {
  width: 50px;
  height: 50px;
  background: green;
  position: absolute;
}

#outer {
  background: red;
  right: -10px;
}
<div id="container">
  <div id="inner"></div>
  <div id="outer"></div>
</div>

Upvotes: 3

Martin Schulz
Martin Schulz

Reputation: 592

If I get you right, you can do it manually:

// assume you have two elements A and B
var ra = A.getBoundingClientRect();
var rb = B.getBoundingClientRect();
// just check corresponding boundaries 
if (ra.left > rb.left && ra.right < rb.right && ra.top > rb.top && ra.bottom < rb.bottom) { // ... }

Upvotes: 2

Related Questions