Skip to content

Instantly share code, notes, and snippets.

@hoai97nam
Created July 12, 2024 06:20
Show Gist options
  • Save hoai97nam/15d7c147eef7d29beaa57a76bdad5da7 to your computer and use it in GitHub Desktop.
Save hoai97nam/15d7c147eef7d29beaa57a76bdad5da7 to your computer and use it in GitHub Desktop.
idea for drag and drop
<!DOCTYPE html>
<html>
<head>
<title>Drag and Drop Example</title>
<style>
#dragableElement {
width: 100px;
height: 50px;
background-color: lightblue;
border: 1px solid blue;
padding: 10px;
cursor: move;
}
#dropableArea {
width: 200px;
height: 100px;
background-color: lightgreen;
border: 1px dashed green;
margin-top: 20px;
padding: 10px;
}
</style>
</head>
<body>
<div id="dragableElement" draggable="true">Drag me</div>
<div id="dropableArea" class="test">Drop here
<div>
blank
</div>
</div>
<script>
function handleDragAndDrop() {
// Get the elements
var dragElement = document.getElementById('dragableElement');
var dropElement = document.getElementById('dropableArea');
// Add event to the draggable element
dragElement.addEventListener('dragstart', (event) => {
event.dataTransfer.setData('text/plain', event.target.id);
});
// Handle drop event on the droppable element
dropElement.addEventListener('drop', (event) => {
event.preventDefault();
// Retrieve data from drag
const dataTransfer = event.dataTransfer.getData('text/plain');
// Find element based on data transfer
const dragableEle = document.getElementById(dataTransfer);
const newDragElement = dragableEle.cloneNode(true);
// Append data to the dropElement (not event.target)
dropElement.appendChild(newDragElement);
});
// Prevent default for dragover to allow drop
dropElement.addEventListener('dragover', (event) => {
event.preventDefault();
});
}
// Attach the event handlers when the page loads
window.onload = handleDragAndDrop;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment