ondrop affects target's parent

901 Views Asked by At

I've got one div in another div. Both div have a ondrop property. When I move an element in the child's dropzone, it calls the ondrop function twice. One time for the child and then one more for the parent.

My problem is : Even if the drop target is in another drop-target container, I don't want the container to be affected by the dropped element. In other words, I don't want the ondrop event to be fired twice.

Can you help me ?

Thanks, Stefan

2

There are 2 best solutions below

0
On BEST ANSWER

You can stop event propagation E.g.

event.stopPropagation();

This will stop the propagation of drop event to parent elements.

P.S. Some code won't hurt.

1
On

In case you are using jQuery - you should use the greedy option of the droppable object:

$( "#draggable" ).draggable();
$( "#droppable" ).droppable({
  greedy: true,
  drop: function(e) {
    alert( "dropped inner" );
  }
});
$( "#droppable-big" ).droppable({
  greedy: true,
  drop: function(e) {
    alert( "dropped" );
  }
});
#draggable {
  width: 50px;
  height: 50px;
  background: #ccc;
}
#droppable-big {
  width: 120px;
  height: 120px;
  background: red;
  color: #fff;
  padding: 60px;
}
#droppable {
  width: 75px;
  height: 75px;
  background: #999;
  color: #fff;
  padding: 10px;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="draggable">Drag me</div>
<div id="droppable-big">
  <div id="droppable">Drop here</div>
</div>