vendredi 27 mars 2020

Else statement within drag and drop function not working in javascript

I did a drag and drop with javascript and some jquery. I added a condition to the drop function but the “else” statement doesn’t seem to work. I want the drop to be allowed only for elements of a certain class, so the else statement should display a “try again” message when an attempt is made to drop an element without that class. The else statement seems to be ignored though.

Here's the code:

$(".farmanimal").attr("draggable", "true").attr("ondragstart", "drag(event)");
$("#farm").attr("ondrop", "drop(event)").attr("ondragover", "allowDrop(event)");


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

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

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("id");
    var className = ev.dataTransfer.getData("class");
    if (className = "farmanimal") {
        ev.target.appendChild(document.getElementById(data));
        $("#goodjob").fadeIn().delay(300).fadeOut().css("display", "flex");
    } else {
        $("#tryagain").fadeIn().delay(300).fadeOut().css("display", "flex");
    }
}

When I try to drop an element with a class other than "farmanimal" I get this error message:

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

Even though appendChild should not be executed since the condition "className = farmanimal" is not true.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire