jQuery dragenter event is fired on every child

15.8k Views Asked by At

I have bound dragenter event on an object that contains some children.

$(document).on('dragenter', '#container', function(e) {
  console.log('dragenter');
});

When I move with dragged file around them, this event is firing repeatedly. What I have expected is firing dragenter only when entering #container element, not every child too.

Is it proper behavior? How can I prevent it?

3

There are 3 best solutions below

2
Felix Kling On BEST ANSWER

You can test whether the element that triggered the event is the container:

var container = $('#container').get(0);

$(document).on('dragenter', '#container', function(event) {
  if(event.target === container) {
      console.log('dragenter');
  }
});

Or if you don't have to use event delegation:

$('#container').on('dragenter', function(event) {
    if(event.target === this) {
        console.log('dragenter');
    }  
});
3
bart s On

try to add stopPropagation

$(document).on('dragenter', '#container', function(e) {
  e.stopPropagation();
  console.log('dragenter');
});
0
Greg Gum On

My answer to this question is to use event capturing instead of event bubbling.

In a nutshell, event capturing "trickles down" from the outer element, to the source element or until e.stopPropagation() is called.

Event bubbling bubbles events up from the source element up through parents until it reaches the document or is stopped with e.stopPropagation().

So, to apply to drag enter, you want the outer div to handle the event, even though it is actually the inner div that is generating the event.

Using event capturing make the ondragenter fire in the Outer Div before the inner div. In the outter div event handler, you call e.stopPropagation. So the inner div event handler never actually runs.

This is how to use jquery to capture the event:

$("#outerDiv").get(0).addEventListener("ondragenter", function(e){e.stopPropagation()}, true);

Note the last parameter.