Search code examples
jquerydragenter

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?


Solution

  • 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');
        }  
    });