Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 drag and drop event based overlay flashing like crazy

I'm trying to implement a drag/drop uploader that marks the dropzone with an overlay (100% width / height absolute element inside the dropzone, looks great when static) when a file is dragged into the window, and removes that marking when the file leaves the window or is dropped outside the dropzone.

The issue is that when the file is dragged into the window, dragover and dragleave events fire like crazy, and the overlay thus flashes in and out like crazy.

window.addEventListener('dragover', handleDrag, false);
window.addEventListener('dragleave', handleStop, false);
window.addEventListener('drop', handleStop, false);
dropzone.addEventListener('drop', handleUpload, false);

function handleDrag(event) {
  // Stop normal browser response.
  event.stopPropagation();
  event.preventDefault();

  if (!window.mysettings.dragging) {
    window.mysettings.dragging = true;
    $('#dropzone').prepend('<div class="overlay">HELLO</div>');
  }
}

function handleStop(event) {
  // Stop normal browser response.
  event.stopPropagation();
  event.preventDefault();

  if (window.mysettings.dragging) {
    window.mysettings.dragging = false;
    $('#dropzone .overlay').remove();
  }
}

function handleUpload(event) {
  // Stop normal browser response.
  event.stopPropagation();
  event.preventDefault();

  if (window.mysettings.dragging) {
    window.mysettings.dragging = false;
    $('#dropzone .overlay').remove();
  }

  // DO MY FILE UPLOAD STUFF HERE
}
like image 998
obrienmd Avatar asked Dec 22 '12 21:12

obrienmd


1 Answers

http://jsbin.com/zabeqigefi/1/edit?css,js,output

Hey,

what's actually going on:

  1. You're prepending/removing item nearly 60 times per second or so.
  2. You can't show full-width overlay over active element! If you're doing so, when overlay is active dragleave will be fired when you're moving mouse around.
  3. I got this from dropbox website - they have four segments to show dropzone activation - like these (it's borders top, bottom, left, right ones):

    <div style="opacity: 0.6; /* display: none; */" class="external-drop-indicator top"></div>
    <div style="opacity: 0.6; display: none;" class="external-drop-indicator right"></div>
    <div style="opacity: 0.6; display: none;" class="external-drop-indicator bottom"></div>
    <div style="opacity: 0.6; display: none;" class="external-drop-indicator left"></div>
    

Good luck!

P.S. - you can always add a class to body instead of creating new nodes, and alter the view of dropzone via css.

like image 167
blade091 Avatar answered Sep 28 '22 03:09

blade091