3

I have this code to detect when a user clicks a file input to upload a file.

$('input:file').click(function() {
    // do stuff here
});

I discovered that many users are dragging files onto the file input to upload a file, and this is not triggering when that happens. I considered mouseover, perhaps in combination with mouseup, but I'm not sure how I would know if the user was holding a file while doing that.

To clarify, I do not need help implementing drag and drop. Also, if possible I want to keep using the file input, and not use a a solution involving dropping onto other elements such as a div. I want the drop to remain on the actual file input.

How can I detect a file being dragged on a file input so that I can react to it?

Goose
  • 4,764
  • 5
  • 45
  • 84
  • Have you tried to get the position of the pointer by using `mousemove()` ? https://api.jquery.com/mousemove/ – elementzero23 Jan 04 '17 at 14:23
  • Try this page http://www.w3schools.com/html/html5_draganddrop.asp – GôTô Jan 04 '17 at 14:25
  • @GôTô that is how to implement dragging on an element. Users are not dragging an element, they are dragging an off browser file, so this doesn't seem to be what I need. Also, w3schools is just awful, incomplete, and often misleading. – Goose Jan 04 '17 at 14:31
  • 1
    @Goose the `drop` event is relevant even in this case, see http://stackoverflow.com/questions/10261989/html5-javascript-drag-and-drop-file-from-external-window-windows-explorer – GôTô Jan 04 '17 at 14:33
  • @GôTô, My file input isn't set up with javascript to allow drag and drop, it's just default browser behavior. Maybe you can post an answer showing how to apply it in my case, because currently I'm not sure what to take from it. – Goose Jan 04 '17 at 14:39

2 Answers2

4

You can react to browser native drag events like dragenter and dragleave

container.addEventListener("dragenter", this.dragenter, true);
container.addEventListener("dragleave", this.dragleave, true);

So you need to define only areas you want to monitor when drag occurs and your actions on this events.

VadimB
  • 5,533
  • 2
  • 34
  • 48
  • Looks like what I need, but my attempt at it did not work, see my updated question to see how I tried to apply it. – Goose Jan 04 '17 at 15:43
  • Seems it works on this fiddle. Please recheck https://jsfiddle.net/3fnatryv/ AddEventListener is native browser event so you need to get DOM element from jQuery search. I use first element [0] – VadimB Jan 04 '17 at 16:09
  • Ah, I see. Thanks! – Goose Jan 04 '17 at 16:09
  • Note on the jsfiddle, because of multiple inputs, I had foreach it like so. https://jsfiddle.net/3fnatryv/1/ – Goose Jan 04 '17 at 16:36
0

I saw that when I drag a file on an input, without any Javascript (except "change" event), I managed to do it.

Plantt
  • 230
  • 1
  • 10