Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if dragged contents is text or files during Javascript dragenter event

Using the dragenter event I show a dropzone on the webpage to have dropped files upload quickly, and it all works well. However, the dropzone also pops up when dragging selected text. How to tell the difference early on?

  1. I know that the drop event exposes all file contents to be iterated using dataTransfer.files, but that's too late. I need it at dragenter, only I see the files array to be empty at all times.

  2. I need full control over look & feel I am not looking for an existing lib.

  3. I can see different values for event.dataTransfer.Clipboard.effectAllowed when dragging text versus files, but values also differ per browser (Chrome vs FF).

  4. MooTools is in place, if that helps.

like image 527
Martin Kool Avatar asked Mar 16 '11 10:03

Martin Kool


2 Answers

Okay, I made enough progress to get differentiating working in Chrome and Firefox (3.6+). It's probably not foolproof but in case anyone might find it useful, here's the code:

  var isFileTransfer = false;
  if (evt.dataTransfer.types) {
    for (var i=0; i<evt.dataTransfer.types.length; i++) {
      if (evt.dataTransfer.types[i] == "Files") {
        isFileTransfer = true;
        break;
      }
    }
  }
like image 92
Martin Kool Avatar answered Nov 14 '22 22:11

Martin Kool


I needed to determine if a file was being dragged into the browser from outside, versus an image being dragged from within the browser window. I did it by listening for dragstart on the document object. When a file is dragged into the browser from outside, the dragstart doesn't fire. So, if it does fire, it means something within the same page is being dragged.

document.addEventListener('dragstart', function() {
    samePageDrag = true;
}, false);

document.addEventListener('dragend', function() {
    if (samePageDrag) {
        samePageDrag = false;
    }
}, false);

With this, you can check the value of samePageDrag after a dragenter or dragover event to determine if the thing being dragged is from outside the browser or not.

like image 27
James M Avatar answered Nov 14 '22 23:11

James M