Question

I am learning about Drag & Drop. I have copied a W3Schools example in JSFiddle.

The W3School example calls preventDefault() in the drop event:

function drop(ev) {
    ev.preventDefault();
    var data=ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(data));
}

Yet, I don't understand the need when reading documentation. When I remove this call, the example still works fine:

function drop(ev) {
    var data=ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(data));
}

So, what is the use of this call to preventDefault()? Do I really need it? If yes why?

Was it helpful?

Solution

It's a way of making sure that you're in full control of what's happening so it's no harm to leave it in because you can never be sure that the browser-specific implementation of the drag and drop api spec won't be working against you, for example as seen here (emphasis mine)

You must cancel the default action for ondragenter and ondragover in order for ondrop to fire. In the case of a div, the default action is not to drop. This can be contrasted with the case of an input type=text element, where the default action is to drop. In order to allow a drag-and-drop action on a div, you must cancel the default action

Note: The linked exampled doesn't actually use e.preventDefault; it uses an older IE-specific method which is window.event.returnValue=false but this has the same effect as e.preventDefault

So I'd be inclined to say that whilst in many cases it won't make a difference, you should include it anyway just to cover the cases for some of your users where it does.

OTHER TIPS

This might be late, but I found a good explanation for your answer.
Yes it is necessary because in the event you're dragging a link, the browser will try to execute that link and not do the drag and drop.

Quote: "In the case of dragging something like a link, we need to prevent the browser's default behavior, which is to navigate to that link. To do this, call e.preventDefault() in the dragover event. Another good practice is to return false in that same handler. Browsers are somewhat inconsistent about needing these, but they don't hurt to add."

Resource: https://www.html5rocks.com/en/tutorials/dnd/basics/

Hope this helps someone like me that questions everything.

Maybe try in every different browser to see if you need it or not. I guess in this simple sample you do not know it but if it was part of a form, I could see a need to prevent a click bubbling up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top