Mark H
Mark H

Reputation: 589

HTML 5 Drag and Drop in correct position

I am trying to make a simple educational game for kids, where they will drag and drop pictures of planets and need to put them in the correct boxes in the correct order.

What I'm trying to figure out is the JS needed to let check the element being dropped on a box is the one that will match that box. The code I have so far allows me to drag and drop but has no check. Here is what I have:

<script type="text/javascript">

    function allowDrop(ev){
        ev.preventDefault();
    }

    function drag(ev){
        ev.dataTransfer.setData("content", ev.target.id);
    }

    function drop(ev){
        ev.preventDefault();
        var image= ev.dataTransfer.getData("content");
        ev.target.appendChild(document.getElementById(image));
    }
</script>

<section id="planetbox">
    <img id="mercuryImg" draggable="true" ondragstart="drag(event)" src="./images/planets/mercury.gif">
</section>

<section id="mercurybox"ondrop="drop(event)" ondragover="allowDrop(event)"> </section>

Any help would be really great. P.S. needs to use HTML 5, CSS and JS only no libraries :)

Upvotes: 1

Views: 2881

Answers (1)

Mark H
Mark H

Reputation: 589

I managed to solve my issue using the code below on the function drop(ev):

function drop(ev){
    ev.preventDefault();
    var image= ev.dataTransfer.getData("content");
    if ( image == ev.target.id) {
           ev.target.appendChild(document.getElementById(image));
    }
    else {

    }
                  }

Upvotes: 1

Related Questions