Salvador Dali
Salvador Dali

Reputation: 222481

Disable dragging images from desktop to html

I was trying to implement a simple HTML5 drag and drop image uploader and everything worked nicely. I have a small div inside html with a simple js event handler which looks like this

$('#uploader').on('dragover', function(e){
  ...
}).on('dragenter', function(e){
  ...
}).on('dragleave', function(e){
  ...
}).on('drop', function(e){
  ...
})

The only small problem is that if a person missed that div and accidentally drops his images outside of it, the browser makes its default event (opening the image in the same tab), which is not really nice.

I tried to disable this by doing

$(elem).on('drop', function(e){
    if (e.originalEvent.preventDefault) e.originalEvent.preventDefault();
    if (e.originalEvent.stopPropagation) e.originalEvent.stopPropagation();
    return false;
})

where I tried different elements like document, body, another parent div, but still if the person is missing the uploader div, the browser opens an image in another page. I also tried to add droppable = 'false' on the elements in HTML markup but with the same result.

Is there any way to prevent this behavior?

Upvotes: 2

Views: 608

Answers (1)

Musa
Musa

Reputation: 97672

Try preventing the dragover event to

$(document).on('dragover drop', function(e){
  return false;
});

Upvotes: 2

Related Questions