This JavaScript code helps you to create a drag-and-drop clone element. When an element is dragged, it’s cloned and dropped into another area. This functionality facilitates creating duplicates of elements by dragging them to a designated drop zone.
You can use this code on websites where you want to allow users to duplicate elements easily. It’s beneficial for creating interactive user interfaces with drag-and-drop functionality. This code enhances user experience by simplifying copying elements on web pages.
How to Create Drag and Drop Clone Element JavaScript
1. Start by defining the HTML structure. Create container elements where elements can be dragged from and dropped into. In our example, we have two <div>
elements with the classes dropArea box1
and dropArea box2
<div class='dropArea box1' ondragover="event.preventDefault()"> <p class='target1' draggable='true'>Target 1</p> <p class='target2' draggable='true'>Target 2</p> <p class='target3' draggable='true'>Target 3</p> </div> <div class='dropArea box2'></div>
2. Style your HTML elements to make them visually appealing and distinguishable. You can customize the look of the draggable items and drop zones according to your design preferences.
.cd__main { display: flex; gap: 20px; justify-content: center; align-items: center; height: 100vh; background: black !important; } .dropArea { display: inline-block; vertical-align: top; width: 400px; min-height: 300px; border: 2px solid white; box-shadow: -3px 2px 1px #757575; padding: 5px; } .dropArea p { color: white; padding: 10px; border-radius: 10px; margin-bottom: 5px; } .target1 { background: #33691ee6; } .target2 { background: #766c13f2; } .target3 { background: #009673db; }
3. Add JavaScript code to enable drag-and-drop cloning. This code listens for drag events, clones the dragged element, and drops the clone into the designated drop zone.
let get = (tag) => document.querySelector(tag); let draggingTarget = null; document.addEventListener("dragstart", function (event) { // console.log(event.target); draggingTarget = event.target; }); get(".box2").addEventListener("dragover", function (event) { // console.log(event.target); event.preventDefault(); }); get(".box2").addEventListener("drop", function (event) { console.log(draggingTarget); let newTarget = draggingTarget.cloneNode(true); console.log(newTarget); this.appendChild(newTarget); });
Congratulations! You’ve successfully implemented drag-and-drop cloning of elements using JavaScript. Feel free to customize the code further to suit your specific requirements and enhance user interaction on your website.