Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery dragenter event is fired on every child

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?

like image 546
hsz Avatar asked Apr 24 '12 12:04

hsz


2 Answers

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');
    }  
});
like image 122
Felix Kling Avatar answered Sep 25 '22 18:09

Felix Kling


try to add stopPropagation

$(document).on('dragenter', '#container', function(e) {
  e.stopPropagation();
  console.log('dragenter');
});
like image 42
bart s Avatar answered Sep 26 '22 18:09

bart s