HTML5 Game - Drag and Drop Drop Zone

Creating the Drop Zone

To mark an element as a drop zone, handle the dragenter and dragover events.

These are two of the events which are targeted at the drop zone.

The following table lists the dragged element events

NameDescription
dragenter Triggered when a dragged element enters the screen space occupied by the drop zone
dragover Triggered when a dragged element moves within the drop zone
dragleave Triggered when a dragged element leaves the drop zone without being dropped
drop Triggered when a dragged element is dropped in the drop zone

The following code shows how to create a drop zone by handling the dragenter and dragover events.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <style>
            #src > * {float:left;}
            #target, #src > img {border: thin solid black; padding: 2px; margin:4px;}
            #target {height: 81px; width: 81px; text-align: center; display: table;}
            #target > p {display: table-cell; vertical-align: middle;}
            #target > img {margin: 1px;}
            img.dragged {background-color: lightgrey;}
            //from w  w w . j a v  a 2 s .c om
        </style>
    </head>
    <body>
        <div id="src">
            <img draggable="true" id="myJet1" src="http://java2s.com/style/demo/jet.png" alt="myJet1"/>
            <img draggable="true" id="myJet2" src="http://java2s.com/style/demo/jet2.png" alt="myJet2"/>
            <img draggable="true" id="myJet3" src="http://java2s.com/style/demo/jet.png" alt="myJet3"/>
            <div id="target">
                <p id="msg">Drop Here</p>
            </div>            
        </div>            
    
        <script>
            let src = document.getElementById("src");
            let target = document.getElementById("target");
            let msg = document.getElementById("msg");
          
            target.ondragenter = handleDrag;
            target.ondragover = handleDrag;
            
            function handleDrag(e) {
                e.preventDefault();
            }
          
            src.ondragstart = function(e) {
                e.target.classList.add("dragged");
            }
            
            src.ondragend = function(e) {
                e.target.classList.remove("dragged");
                msg.innerHTML = "Drop Here";
            }
          
            src.ondrag = function(e) {
                msg.innerHTML = e.target.id;
            }
        </script>
    </body>
</html>