<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag and Drop with Validation</title>
<style>
body {
font-family: Arial, sans-serif;
}
.container {
display: flex;
justify-content: space-around;
padding: 20px;
}
.box {
width: 100px;
height: 100px;
background-color: #f0f0f0;
border: 1px solid #ccc;
text-align: center;
line-height: 100px;
cursor: pointer;
}
.box.draggable {
background-color: #d3d3d3;
}
#box1 {
background-color: #f44336;
color: white;
}
#box2 {
background-color: #2196f3;
color: white;
}
</style>
</head>
<body>
<div class="container">
<div id="box1" class="box" draggable="true" ondragstart="drag(event)">Box 1</div>
<div id="box2" class="box" draggable="true" ondragstart="drag(event)">Box 2</div>
</div>
<div class="container">
<div id="dropbox1" class="box droppable" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div id="dropbox2" class="box droppable" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</div>
<script>
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function allowDrop(ev) {
ev.preventDefault();
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
var draggedBox = document.getElementById(data);
var dropzone = ev.target;
if (draggedBox.id === dropzone.id.replace("drop", "")) {
dropzone.appendChild(draggedBox);
} else {
alert("Invalid drop. Please drop the box with the same ID.");
}
}
</script>
</body>
</html>
drop(ev)
checks if the dragged box's ID matches the drop zone's ID. If they don't match, an alert is shown indicating an invalid drop.You're welcome! If you have any more questions or need further assistance in the future, feel free to ask. Have a great day!thanks
I apologize for the oversight. Let's address the issues you mentioned:image from unsepbox to box container wasnt stay still in it and modal doesnt work too
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
var draggedImage = document.getElementById(data);
var dropzone = ev.target;
if (draggedImage.id === "unsepbox") {
dropzone.appendChild(draggedImage);
} else {
alert("Invalid drop. Please drop the image into the box container.");
}
}
<!-- Modal HTML -->
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>This is the modal content.</p>
</div>
</div>
<!-- JavaScript for modal -->
<script>
var modal = document.getElementById("myModal");
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>