Skip to content Skip to sidebar Skip to footer

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 fa

Solution 1:

The ondragover event needs to be canceled in Google Chrome and Safari to allow firing the ondrop event.


Solution 2:

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>

Post a Comment for "How To Stop Redirecting After `drop` Event?"