2

Following the MDN guide Selecting files using drag and drop, the code is:

var dropbox;

dropbox = document.getElementById("dropbox");
dropbox.addEventListener("dragenter", dragenter, false);
dropbox.addEventListener("dragover", dragover, false);
dropbox.addEventListener("drop", drop, false);

function dragenter(e) {
  e.stopPropagation();
  e.preventDefault();
}

function dragover(e) {
  e.stopPropagation();
  e.preventDefault();
}

function drop(e) {
  e.stopPropagation();
  e.preventDefault();

  var dt = e.dataTransfer;
  var files = dt.files;

  handleFiles(files);
}

I understand that I've to use preventDefault() to avoid the browser from open the file that I drop. But why do I've to use stopPropagation()? What bubbling/capturing am I stopping here?

Angel Luis
  • 322
  • 4
  • 14
  • this might be sort of related? https://stackoverflow.com/questions/11072002/jquery-e-stoppropagation-how-to-use-without-breaking-dropbox-functionality-a – Sterling Archer Jan 29 '18 at 17:26
  • @SterlingArcher It doesn't affect in nothing if I use or if I don't use `stopPropagation()`. I can drop infinite files, it only listen the event that it should (it doesn't affect to any parent element...). So I haven't found any use for `stopPropagation()`. – Angel Luis Jan 29 '18 at 17:36

1 Answers1

0

It means 'if there any elements in the DOM containing your "dropbox" id element with matching named event handler functions attached, then they are not notified about the event'.

There is a good example at the Mozilla javascript documentation on the DOM

which has an html table containing a table data cell, both of which have an event handler attached. If you remove the ev.stopPropogation() (at line 17), both event handler functions would be called, with it there, only the table cell event handler is called.

--

There is also a similar SO question at What's the difference between event.stopPropagation and event.preventDefault?

stackuser83
  • 2,012
  • 1
  • 24
  • 41
  • Yes, I've studied that case some time ago to understand the capturing behaviour. But in this case we only have a element wich contains the "dropbox". And it's very strange put a child element inside a dropbox. – Angel Luis Jan 29 '18 at 17:48
  • Maybe there is a stretch explanation of why someone might want multiple "drop" event handlers in multiple contained html elements, but not for a generic scenario. Usually there would be very few or only one such event handlers in a DOM tree, so omitting the stopPropagation would not have effect. – stackuser83 Jan 29 '18 at 17:59
  • 1
    @stackuser83 this shouldn't be a usecase because elements should never share the same ID – Sterling Archer Jan 29 '18 at 18:22