webta.st.ic
webta.st.ic

Reputation: 5169

Detect if dragged element is overlapping another

I have two elements with the class .panel. They can have an additional class .panel--expanded. I also have an element, which is draggable. What I want to do is to detect, if the draggable element is overlapping the panel element without the .panel--expanded class. I tried to solve this with the IntersectionObserver. What I expect was, when I set the root as the panel without the expanded class, the target callback should throw the alert, if dragging over the panel without the expanded class. On the other way, it should not throw the alert, if I drag it over the panel with the expanded class. Seems that I understood something wrong from how the IntersectionObserver works. Is it even possible with it, or did I miss something? At the moment, no alert appears in both cases.

Here is my snippet:

let target = document.querySelector('.draggable');

let callback = (entries, observer) => {
  entries.forEach(entry => {
     if (entry.isIntersecting) {
       alert('OVERLAPPING!');
     }
  }); 
};

let options = {
  root: document.querySelector('.panel:not(.panel--expanded)')
};

let observer = new IntersectionObserver(callback, options);
observer.observe(target);
.panel {
  background-color: lightblue;
  height: 100px;
  margin: 50px 0px;
  width: 500px;
}

.panel--expanded {
  background-color: coral;
}

.draggable {
  background-color: lightgreen;
  box-shadow: 5px 5px 5px 5px lightgray;
  height: 50px;
  width: 300px;
}
<div class="panel">panel without panel--expanded class</div>
<div class="draggable" draggable="true">draggable element</div>
<div class="panel panel--expanded">panel with panel--expanded class</div>

Upvotes: 3

Views: 3378

Answers (1)

majusebetter
majusebetter

Reputation: 1592

I think the IntersectionObserver is not the right tool for this task, since the element being dragged is a visual representation of the source element created by the browser - i.e. the actual element stays at its current position. That's why there is no intersection detected by the observer.

You could use the ondragover event handler on your node(s) to detect the intersection, like this:

function handleDrag(event) {
    if (!event.target.classList.contains('.panel--expanded')) {
        console.log('OVERLAPPING!');  
    } 
}
.panel {
  background-color: lightblue;
  height: 100px;
  margin: 50px 0px;
  width: 500px;
}

.panel--expanded {
  background-color: coral;
}

.draggable {
  background-color: lightgreen;
  box-shadow: 5px 5px 5px 5px lightgray;
  height: 50px;
  width: 300px;
}
<div class="panel" ondragover="handleDrag(event)">panel without panel--expanded class</div>
<div class="draggable" draggable="true">draggable element</div>
<div class="panel panel--expanded" ondragover="handleDrag(event)">panel with panel--expanded class</div>

Upvotes: 3

Related Questions