Javascript DOM Drag Leave Event
<!DOCTYPE html> <html lang="en"> <head> <style> [data-drop-target] { // w w w . j a v a 2 s .c o m height: 400px; width: 200px; margin: 2px; background-color: gainsboro; float: left; } .drag-enter { border: 2px dashed #000; } .box { width: 200px; height: 200px; } .navy { background-color: navy; } .red { background-color: red; } </style> </head> <body> <div data-drop-target="true"> <div id="box1" draggable="true" class="box navy"></div> <div id="box2" draggable="true" class="box red"></div> </div> <div data-drop-target="true"></div> <script> function getRandomMessage() { let messages = [ "A", "B", "C" ]; return messages[Math.floor((Math.random() * 3) + 0)]; } function handleDragStart(e) { let data = { elementId: this.id, message: getRandomMessage() }; e.dataTransfer.setData("text", JSON.stringify(data)); } function handleDragEnterLeave(e) { if (e.type == "dragenter") { this.className = "drag-enter"; } else { this.className = ""; } } function handleOverDrop(e) { e.preventDefault(); if (e.type != "drop") { return; } let json = e.dataTransfer.getData("text"); let data = JSON.parse(json); let draggedEl = document.getElementById(data.elementId); if (draggedEl.parentNode == this) { this.className = ""; return; } draggedEl.parentNode.removeChild(draggedEl); this.appendChild(draggedEl); this.className = ""; console.log(data.message); } let draggable = document.querySelectorAll("[draggable]"); let targets = document.querySelectorAll("[data-drop-target]"); for (let i = 0; i < draggable.length; i++) { draggable[i].addEventListener("dragstart", handleDragStart); } for (i = 0; i < targets.length; i++) { targets[i].addEventListener("dragover", handleOverDrop); targets[i].addEventListener("drop", handleOverDrop); targets[i].addEventListener("dragenter", handleDragEnterLeave); targets[i].addEventListener("dragleave", handleDragEnterLeave); } </script> </body> </html>