javascripthtmldrag-and-droppreventdefault

Is call to preventDefault() really necessary on drop event?


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?


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.