Overview
I want to attach an event to an element for handling file drag and drop events, but it seems like this event is also being attached to all the child elements. For example,
$('#dragtarget').on('dragenter', function() {
console.log('dragenter');
});
... if I drag files over any elements that are children of the #dragtarget
element, the console will output dragenter
. So if I attach this event to document
or window
, the event will fire when hovering over any element on the page.
The same thing happens with dragleave
, except when leaving child elements.
Question
Why is this happening? Is there away to attach this event to only the element intended? If not, is there a way to detach the event from all child elements?
jsFiddle
Here's an example fiddle to tinker with: http://jsfiddle.net/UnsungHero97/ePLV6/7/
Notice how the border changes to solid when you drag files over the box, but back to dashed when hovering over the text
I want the border to change to solid when dragging files over the box, no matter if I'm hovering over the text within the box
Here's the code from the fiddle for just in case:
HTML
<div id="dragtarget">
<span>File over/out here</span>
<br/><br/>
<span>more text here</span>
</div>
JS
// I expect only the #dragtarget element to fire the 'dragenter' and 'dragleave' events,
// not the child elements
$('#dragtarget').on('dragenter', function() {
$(this).css({borderStyle: 'solid'});
event.stopPropagation();
event.preventDefault();
return false;
}).on('dragleave', function() {
$(this).css({borderStyle: 'dashed'});
event.stopPropagation();
event.preventDefault();
return false;
});