Kristian Daugaard Kristian Daugaard - 3 months ago 9x
Javascript Question

Drag and drop Javascript HTML5

I am trying to make a drag and drop feature using javascript and HTML5, no jQuery. And I just cannot see what is wrong. Been looking at this for a long time and can't see where i failed. Can someone find it?

function doFirst(){
mypic = document.getElementById('dragapple');
mypic.addEventListener("dragstart", startDrag, false);

leftbox = document.getElementById('leftbox');
leftbox.addEventListener("dragenter", function(e){e.preventDefault}, false);
leftbox.addEventListener("dragover", function(e){e.preventDefault}, false);
leftbox.addEventListener("drop", dropped, false);
function startDrag(e){
var code = '<img id="dragapple" src="stealeripsum.png">';
e.dataTransfer.setData('Text', code);
function dropped(e){
leftbox.innerHTML = e.dataTransfer.getData('Text');
window.addEventListener("load", doFirst, false);



It's always the little things that catch us in the end. Inside your definition for the "dragover" event listener, you need to provide an argument list () to e.PreventDefault:

leftbox.addEventListener("dragenter", function(e){e.preventDefault();}, false);
leftbox.addEventListener("dragover", function(e){e.preventDefault();}, false);

That way, the browser will stop the default event response (which is to dis-allow dropping) and let your drop operation complete. Here's my silly jsFiddle demo illustrating success. The blue square is the #dragapple.