Ad

Drag And Drop HTML5 Not Working?

- 1 answer

I am trying to understand the drag and drop for html5, I can get it to drag and have the element that is suppose to take the dragged element accept it. However I cant get the ondrag or ondragenter, or at least the functions those events call to work I'm not really sure what I'm doing wrong.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Week 3 Drag and Drop</title>
<link rel="stylesheet" type="text/css" target="_blank" rel="nofollow noreferrer" href="Week3DragAndDropCSS.css">
<script src="Week3DragAndDropJS.js"></script>
</head>
<body>
<header>
    <h1>Week 3 Drag and Drop</h1>
</header>

<div style="height:200px;width:200px;background: red"    
    id="obj1"draggable="true"></div>
<div style="height:200px;width:200px;background:
    green"id="obj2"draggable="true"></div>
<div style="height:200px;width:200px;background: orange" 
    id="obj3"draggable="true"></div>    
<div style="height:200px;width:200px;background-image: url
    ('trash.png');background-repeat: no-repeat;" id="trashCan" 
    ondragover="allowDrop(event)" ondragenter="setBorder(event,'5px')" 
    ondragleave="setBorder(event,'2px')" ondrop="drop(event)"></div>




<footer>

</footer>

    </body>

    </html>

Then here is my js:

function drag(evt){
evt.dataTransfer.setData("color", ev.target.background);
}
function allowDrop(evt){
evt.preventDefault();
}
function drop(evt){
evt.preventDefault();
var color = evt.dataTransfer.getData("color");
evt.currentTarget.style.background = color; 

}
function setBorder(evt,size){
evt.currentTarget.border = (size +"solid black");
}
Ad

Answer

minor syntax mistakes reffer following fiddle

function drag(evt){

evt.dataTransfer.setData("color", 
evt.target.style.backgroundColor);
}
function allowDrop(evt){
evt.preventDefault();
}
function drop(evt){
evt.preventDefault();
var color = evt.dataTransfer.getData("color");
evt.currentTarget.style.background = color; 

}
function setBorder(evt,size){
evt.currentTarget.style.border = (size +" solid black");
}
<body>
<header>
    <h1>Week 3 Drag and Drop</h1>
</header>

<div style="height:200px;width:200px;background: red"    
    id="obj1"draggable="true" ondragstart="drag(event)"></div>
<div style="height:200px;width:200px;background:
    green"id="obj2"draggable="true" ondragstart="drag(event)"></div>
<div style="height:200px;width:200px;background: orange" 
    id="obj3"draggable="true" ondragstart="drag(event)"></div>    
<div style="height:200px;width:200px;background-image: url
    ('trash.png');background-repeat: no-repeat;" id="trashCan" 
    ondragover="allowDrop(event)" ondragenter="setBorder(event,'5px')" 
    ondragleave="setBorder(event,'2px')" ondrop="drop(event)"></div>




<footer>

</footer>

    </body>

Ad
source: stackoverflow.com
Ad