Reputation: 1081
I have this script that drags a div into another div:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
.content {
width: 300px;
height: 300px;
border: 1px solid black;
}
#dragme {
height:50px;
width:50px;
background-color: blue;
}
</style>
</head>
<body>
<div class="content" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div id="dragme" draggable="true" ondragstart="drag(event)">Drag me!</div>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("dragged-id", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("dragged-id");
ev.target.appendChild(document.getElementById(data));
}
</script>
</body>
</html>
It all works fine, however when I change the "dragme" div from id to class, it stops working. It makes absolutely no sense to me. Please help ?
Upvotes: 1
Views: 1305
Reputation: 44601
<body>
<div class="content" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div class="dragme" draggable="true" ondragstart="drag(event)">Drag me!</div>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("dragged-id", ev.target.className);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("dragged-id");
ev.target.appendChild(document.getElementsByClassName(data)[0]);
}
</script>
</body>
CSS:
.dragme {
height:50px;
width:50px;
background-color: blue;
}
Upvotes: 3