36

Firefox doesn't properly trigger the dragleave event when dragging outside of the window:

https://bugzilla.mozilla.org/show_bug.cgi?id=665704

https://bugzilla.mozilla.org/show_bug.cgi?id=656164

I'm trying to develop a workaround for this (which I know is possible because Gmail is doing it), but the only thing I can come up with seems really hackish.

One way of knowing when dragging outside the window has occurred it to wait for the dragover event to stop firing (because dragover fires constantly during a drag and drop operation). Here's how I'm doing that:

var timeout;

function dragleaveFunctionality() {
  // do stuff
}

function firefoxTimeoutHack() {
  clearTimeout(timeout);
  timeout = setTimeout(dragleaveFunctionality, 200);
}

$(document).on('dragover', firefoxTimeoutHack);

This code is essentially creating and clearing a timeout over and over again. The 200 millisecond timeout will not be reached unless the dragover event stops firing.

While this works, I don't like the idea of using a timeout for this purpose. It feels wrong. It also means there's a slight lag before the "dropzone" styling goes away.

The other idea I had was to detect when the mouse leaves the window, but the normal ways of doing that don't seem to work during drag and drop operations.

Does anyone out there have a better way of doing this?

UPDATE:

Here's the code I am using:

 $(function() {
          var counter = 0;
          $(document).on('dragenter', function(e) {
            counter += 1;
            console.log(counter, e.target);
          });
          $(document).on('dragleave', function(e) {
            counter -= 1;
            console.log(counter, e.target);
          });
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Open up the console and look at what number is reporting when dragging files in and out of the window. The number should always be 0 when leaving the window, but in Firefox it's not.</p>
Nicolas
  • 8,077
  • 4
  • 21
  • 51
Philip Walton
  • 29,693
  • 16
  • 60
  • 84
  • The problem appears fixed in Firefox 11 - what version are you targeting? – Eli Sand Apr 23 '12 at 02:40
  • I'm still seeing it on Firefox 11, and according to the bug reports, it hasn't been fixed. I'll see if I can put together a demo to link to. – Philip Walton Apr 23 '12 at 02:49
  • Please - that may help pinpoint the issue. I made a simple page and bound to dragleave on document and it fired for me when my dragging left the document. I also found [this](http://www.quirksmode.org/blog/archives/2009/09/the_html5_drag.html)... interesting that some events having events bound can affect others firing – Eli Sand Apr 23 '12 at 03:09
  • What I see is that the handler fires twice on enter, and once on leave. I don't know if I have the same problem. Firefox 11.0. – pbfy0 Apr 23 '12 at 22:13
  • What if you launch Firefox in safemode (no plug-ins)? I just tried your demo page as-is and I got 1's on enter, 0's on exit just as it should. – Eli Sand Apr 24 '12 at 00:28
  • @EliSand I'm not sure what you're seeing, but I have the same problem in Firefox 11 on Windows and OS X, in both regular and safe modes. – Philip Walton Apr 24 '12 at 02:31
  • @PhilipWalton - last few questions... did you try testing from a fresh profile with no plug-ins? Your test page has the JS inline in the body; what if you put it in the head and run on document ready and use `bind()` instead of `on()`? What types of things have you tried dragging (selected text, files)? I've tried every test case I've found online and in bug reports and they all work for me (Windows 7x64 & FF 11) – Eli Sand Apr 24 '12 at 23:18
  • @EliSand I have no idea why you're not seeing it. I've tried it on Window 7x64 with FF11 and I still see the problem. Factors like `bind()` vs `on()` have nothing to do with this. – Philip Walton Apr 25 '12 at 18:06
  • @PhilipWalton - no idea either. I'm all out of ideas at this point. I mentioned the `bind()` vs `on()` thing just for the sake of grabbing any last straws available - you never know... – Eli Sand Apr 26 '12 at 01:09

5 Answers5

58

I've found a solution. The problem was not so much that the dragleave event wasn't firing; rather, the dragenter event was firing twice when first dragging a file into the window (and additionally sometimes when dragging over certain elements). My original solution was to use a counter to track when the final dragleave event was occuring, but the double firing of dragenter events was messing up the count. (Why couldn't I just listen for dragleave you ask? Well, because dragleave functions very similarly to mouseout in that it fires not only when leaving the element but also when entering a child element. Thus, when dragleave fires, your mouse may very well still be within the bounds of the original element.)

The solution I came up with was to keep track of which elements dragenter and dragleave had been triggered on. Since events propagate up to the document, listening for dragenter and dragleave on a particular element will capture not only events on that element but also events on its children.

So, I created a jQuery collection $() to keep track of what events were fired on what elements. I added the event.target to the collection whenever dragenter was fired, and I removed event.target from the collection whenever dragleave happened. The idea was that if the collection were empty it would mean I had actually left the original element because if I were entering a child element instead, at least one element (the child) would still be in the jQuery collection. Lastly, when the drop event is fired, I want to reset the collection to empty, so it's ready to go when the next dragenter event occurs.

jQuery also saves a lot of extra work because it automatically does duplicate checking, so event.target doesn't get added twice, even when Firefox was incorrectly double-invoking dragenter.

Phew, anyway, here's a basic version of the code I ended up using. I've put it into a simple jQuery plugin if anyone else is interested in using it. Basically, you call .draghover on any element, and draghoverstart is triggered when first dragging into the element, and draghoverend is triggered once the drag has actually left it.

// The plugin code
$.fn.draghover = function(options) {
  return this.each(function() {

    var collection = $(),
        self = $(this);

    self.on('dragenter', function(e) {
      if (collection.length === 0) {
        self.trigger('draghoverstart');
      }
      collection = collection.add(e.target);
    });

    self.on('dragleave drop', function(e) {
      collection = collection.not(e.target);
      if (collection.length === 0) {
        self.trigger('draghoverend');
      }
    });
  });
};

// Now that we have a plugin, we can listen for the new events 
$(window).draghover().on({
  'draghoverstart': function() {
    console.log('A file has been dragged into the window.');
  },
  'draghoverend': function() {
    console.log('A file has been dragged out of window.');
  }
});

Without jQuery

To handle this without jQuery you can do something like this:

// I want to handle drag leaving on the document
let count = 0
onDragEnter = (event) => {
  if (event.currentTarget === document) {
    count += 1
  }
}

onDragLeave = (event) => {
  if (event.currentTarget === document) {
     count += 0
  }

  if (count === 0) {
    // Handle drag leave.
  }
}
Sanborn
  • 289
  • 1
  • 2
  • 14
Philip Walton
  • 29,693
  • 16
  • 60
  • 84
  • 1
    I added `drop` to the `dragleave` handler as this should probably also count as a `draghoverend`. Gist with comments: https://gist.github.com/3794126 – meleyal Sep 27 '12 at 14:06
  • @meleyal, that's totally fine. FWIW, I didn't include it originally because the drop event occurs consistently across all browsers and I didn't feel the need to normalize it. – Philip Walton Sep 27 '12 at 17:07
  • I ran into the case where the last element in the collection was not getting removed. This was due to `drop` being the last event to fire, so then the `dragleave` doesn't get called. – meleyal Sep 28 '12 at 07:26
  • This seems to be a bit buggy for me in both Chrome and Firefox. Seems to be some elements on the page I've yet to identify that trigger a leave. It does make the issue much more bearable however compared to the vanilla `dragleave` implementation. Will report back if I can solve it. – DanH Jan 02 '13 at 09:59
  • The problem I'm having is that Firefox is triggering `draghoverend` when dragging files over text nodes. Here's a fiddle to demonstrate http://jsfiddle.net/tusRy/4/. The plugin works perfectly for enter/leaving the window however. – DanH Jan 07 '13 at 10:41
  • I decided to open another question for this: http://stackoverflow.com/questions/14194324/firefox-firing-dragleave-when-dragging-over-text – DanH Jan 07 '13 at 10:58
  • @meleyal actually, you're totally right! I just encountered the issue you pointed out on a project I'm working on. I've updated the answer to reflect this. Thanks! – Philip Walton Oct 10 '13 at 18:50
  • This works alright, but it breaks when trying to track two elements (eg. window and class). This worked better for me: https://github.com/lolmaus/jquery.dragbetter – d_rail Nov 14 '14 at 02:24
  • 3
    This approach still works, but the solution itself needs a minor change. Specifically all references to e.target need to instead be e.originalEvent.target. This solves the issue where #text elements (the contents of a p tag) trigger dragenter/dragleave within firefox. jQuery event normalizes these references to

    , which causes issues with the tabulation scheme suggested here. With this change dragend/dragleave events seem to work as expected.

    – kamelkev Apr 27 '16 at 03:08
3

Depending on what you wish to accomplish you can get around this issue by using the :-moz-drag-over pseudo-class that is only available in Firefox which lets you react to a file being dragged over an element.

Take a look at this simple demo http://codepen.io/ryanseddon/pen/Ccsua

.dragover {
    background: red;
    width: 500px;
    height: 300px;
}
.dragover:-moz-drag-over {
    background: green;
}
Ryan Seddon
  • 147
  • 1
  • 4
0

Inspired by @PhilipWalton 's code, I simplified the jQuery plugin code.

$.fn.draghover = function(fnIn, fnOut) {
    return this.each(function() {
        var n = 0;
        $(this).on('dragenter', function(e) {
            (++n, n==1) && fnIn && fnIn.call(this, e);
        }).on('dragleave drop', function(e) {
            (--n, n==0) && fnOut && fnOut.call(this, e);
        });
    });
};

Now you can use the jquery plugin like jquery hover method:

// Testing code 1
$(window).draghover(function() {
    console.log('into window');
}, function() {
    console.log('out of window');
});

// Testing code 2
$('#d1').draghover(function() {
    console.log('into #d1');
}, function() {
    console.log('out of #d1');
});
cuixiping
  • 24,167
  • 8
  • 82
  • 93
0

only solution that has worked for me and took me a few goes hope this helps someone!

note when cloning you need to deepclone with events and data:

HTML:

<div class="dropbox"><p>Child element still works!</p></div>

<div class="dropbox"></div>

<div class="dropbox"></div>

jQuery

$('.dropbox').each(function(idx, el){
    $(this).data("counter" , 0);
});

$('.dropbox').clone(true,true).appendTo($('body');

$('dropbox').on({
    dragenter : function(e){
        $(this).data().counter++;
        <!-- YOUR CODE HERE -->
    },
      dragleave: function(e){

        $(this).data().counter--;

         if($(this).data().counter === 0)
              <!-- THEN RUN YOUR CODE HERE -->
    }
});
Bass
  • 1
-1
addEvent(document, "mouseout", function(e) {
    e = e ? e : window.event;
    var from = e.relatedTarget || e.toElement;
    if (!from || from.nodeName == "HTML") {
        // stop your drag event here
        // for now we can just use an alert
        alert("left window");
    }
});

This is copied from How can I detect when the mouse leaves the window?. addEvent is just crossbrowser addEventListener.

Community
  • 1
  • 1
pbfy0
  • 616
  • 4
  • 13