Skip to content
Advertisement

Javascript: move a DIV and detect when it’s fully inside another DIV?

I have to create a UI where the user can click buttons to move a DIV (the gray box) in preset increments by clicking the 4 buttons. Further, i need to detect when they have moved it completely “inside” the other DIV (dotted red line).

enter image description here

Moving the div seems straightforward enough, but I am confused as to the best way to detect if the gray box is fully inside the dotted box.

I can do this ad HTML or as an SVG, but all my research has shown conflicting results and although detecting an intersection seems simple, I have found nothing on detecting being fully contained in the bounds of a different rect.

Suggestions on an approach appreciated.

Advertisement

Answer

You need to use the Intersection Observer API

const options = {
  root: document.querySelector('CONTAINER SELECTOR'),
  rootMargin: '0px',
  threshold: 1.0
}

const targetToWatch = document.querySelector('INSIDE ITEM SELECTOR');

let callback = (entries, observer) => {
  entries.forEach(entry => {
    // Each entry describes an intersection change for one observed
    // target element:
    //   entry.boundingClientRect
    //   entry.intersectionRatio
    //   entry.intersectionRect
    //   entry.isIntersecting
    //   entry.rootBounds
    //   entry.target
    //   entry.time
  });
};

const observer = new IntersectionObserver(callback, options);
observer.observe(targetToWatch);

You need then to check various entry. parameters to know if the element is inside.

Advertisement