HTML5 DragDrop Enter and Leave event is called one after another

Viewed 31

I have a very simple drag & drop effect by changing the class name when the drag is entering (or over) and when it is leaving. However, I am experiencing continuous entering and leaving.

Look at this simple HTML code

<div class="box">
  <div class="childbox"></div>
</div>

This is my CSS

.box {
  position: relative;
  width: 80%;
  height: 300px;
  border: 1px solid black;
}

.box.dragover:after {
  position: absolute;
  background-color: rgba(0, 255, 0, 0.05);
  content: '';
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.childbox {
  position: relative;
  width: 100%;
  height: 100%;
}

This is my script

$('.box').on('drag dragstart dragend dragover dragenter dragleave drop', function(e) {
  e.preventDefault();
  e.stopPropagation();
}).bind('dragover dragenter', function(e) {
  e.stopPropagation();
  $(this).addClass('dragover');
  console.log('\nEvent: ' + e.originalEvent.type + ' --- Target: ' + this.className);
}).bind('dragleave dragend drop', function(e) {
  e.stopPropagation();
  $(this).removeClass('dragover');
  console.log('\nEvent: ' + e.originalEvent.type + ' --- Target: ' + this.className);
});

I've created the jsfiddle https://jsfiddle.net/n71udevm/1/ and if you tried to drag any file into the box, it will create a blink effect from green to white. This is because the dragenter and dragleave event is called one after another.

I suspect it caused by box.dragover:after. Any idea on how to fix it?

Thanks...

1 Answers

Add pointer-events: none to the :after. This will make :after to not response to mouse events including all the events you mention in your code.

.box.dragover:after {
  pointer-events: none; /* <- here */
}

$('.box').on('drag dragstart dragend dragover dragenter dragleave drop', function (e) {
  e.preventDefault();
  e.stopPropagation();
}).bind('dragover dragenter', function (e) {
  e.stopPropagation();
  $(this).addClass('dragover');
  console.log('\nEvent: ' + e.originalEvent.type + '   ---   Target: ' + this.className);
}).bind('dragleave dragend drop', function (e) {
  e.stopPropagation();
  $(this).removeClass('dragover');
  console.log('\nEvent: ' + e.originalEvent.type + '   ---   Target: ' + this.className);
})
.box {
  position: relative;
  width: 80%;
  height: 300px;
  border: 1px solid black;
}

.box.dragover:after {
  pointer-events: none;
  position: absolute;
  background-color: rgba(0, 255, 0, 0.05);
  content: '';
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.childbox {
  position: relative;
  width: 100%;
  height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
  <div class="childbox">
  
  </div>
</div>

https://jsfiddle.net/moshfeu/24bvshan/

Related