I copied this code from w3schools. But the editor does cross out the word event.
The code worked. But I am not sure if I should change something because of the crossing out.
I want to make and application with this technique.
Picture of the crossed out word
<!DOCTYPE HTML>
<html>
<head>
<style>
#div1, #div2 {
float: left;
width: 100px;
height: 35px;
margin: 10px;
padding: 10px;
border: 1px solid black;
}
</style>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<h2>Drag and Drop</h2>
<p>Drag the image back and forth between the two div elements.</p>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
<img id="drag1" src="https://cdn.pixabay.com/photo/2020/12/02/01/06/chipmunk-5795916__340.jpg" draggable="true" ondragstart="drag(event)" width="336" height="69">
</div>
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</body>
</html>
CodePudding user response:
You'd better not use inline functions in your HTML code, use addEventListener
for better code.
let dragged = null;
const source = document.getElementById("draggable");
source.addEventListener("dragstart", (event) => {
// store a ref. on the dragged elem
dragged = event.target;
});
const target = document.querySelectorAll(".dropzone");
target.forEach(function (item) {
item.addEventListener("dragover", (event) => {
// prevent default to allow drop
event.preventDefault();
});
item.addEventListener("drop", (event) => {
// prevent default action (open as link for some elements)
event.preventDefault();
// move dragged element to the selected drop target
if (event.target.className === "dropzone") {
dragged.parentNode.removeChild(dragged);
event.target.appendChild(dragged);
}
});
});
body {
/* Prevent the user selecting text in the example */
user-select: none;
}
#draggable {
text-align: center;
background: white;
}
.dropzone {
width: 100px;
height: 40px;
background: lightblue;
margin: 10px;
padding: 10px;
}
<div >
<img id="draggable" src="https://cdn.pixabay.com/photo/2020/12/02/01/06/chipmunk-5795916__340.jpg" draggable="true" width="100" height="35">
</div>
<div ></div>