Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop redirecting after `drop` event?

After dropping a file into a div in Firefox, the webpage will be redirected to this file. I tried to stop this propagation using jQuery's e.preventDefault() in drop handler, and failed.

See this demo, dropping a file into #test won't redirect the webpage, but dropping into #test1 will, I want to know why. Should I always bind handlers to dragenter, dragover, dragleave and drop to prevent propagation after drop?

update:

I found some tips on html5doctor:

To tell the browser we can drop in this element, all we have to do is cancel the dragover event. However, since IE behaves differently, we need to do the same thing for the dragenter event.

And Mozilla claims:

A listener for the dragenter and dragover events are used to indicate valid drop targets, that is, places where dragged items may be dropped.

But I test this demo on firefox, #test works and #test1 doesn't, seems Mozilla made a mistake, and html5doctor is right: Firefox needs dragover only to make drop work.

like image 368
Rufus Avatar asked Jan 20 '12 07:01

Rufus


People also ask

Can you stop a redirect?

Redirection is part of a website's code, and you can't completely disable it, but a workaround in your Internet settings gives you control over which redirects you want to follow. With the right settings, your computer blocks certain sites and asks for permission before redirecting.


1 Answers

I noticed that it wasn't just enough to cancel onDragOver, but I also had to cancel onDragDrop and onDragLeave. Below, I'm showing logging indicating what behavior the user is doing :

<script type="text/javascript">

    var handledragleave = function handleDragLeave(e) {
            console.log("Floating away.  Do code here when float away happens.");
            return this.cancelDefaultBehavior(e);
    }

    var handledragdrop = function handleDrop(e) {
            console.log("Dropping.  Do code here when drop happens.");
            return this.cancelDefaultBehavior(e);
    }

    var handledragover = function handleDragOver(e) {
            console.log("Floating over.  Do code here when float over happens.");
            return this.cancelDefaultBehavior(e);
    }

    cancelDefaultBehavior(e) {
            e.preventDefault();
            e.stopPropagation();
            return false;
    }

$('.your-element-being-dragged-to')
    .on('DragLeave', handledragleave)
    .on('DragDrop', handledragdrop)
    .on('DragOver', handledragover);

</script>

And then your element...

<p class="your-element-being-dragged-to">Drag something here!</p>
like image 166
HoldOffHunger Avatar answered Oct 05 '22 23:10

HoldOffHunger