I know it's not possible to remove an inherited event listener with removeEventListener, but I saw some other questions were they recommended setting the event listeners to null and then assigning a random function to them. Here, I want to create some drop zones and some draggable cards. You would grab the card and drop them in one of the fields and nowhere else. Yet, after I drop them in one, they become droppable fields themselves, as they inherit the event listeners from the drop zones. Here's my code: HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<link rel="stylesheet" href="./style.css">
<script src="./script.js" defer></script>
</head>
<body>
<h2 class="dragHeader">Drag and drop test 2</h2>
<div class="dragWrapper">
<div class="dragBase">
<div class="dragCard dragRed" draggable="true" id="dragBox1">1.</div>
<div class="dragCard dragGreen" draggable="true" id="dragBox2">2.</div>
<div class="dragCard dragBlue" draggable="true" id="dragBox3">3.</div>
</div>
<div class="drag drag2" id="drag2_1"></div>
<div class="drag drag2" id="drag2_2"></div>
<div class="drag drag2" id="drag2_3"></div>
</div>
</body>
</html>
javaScript:
function dragStart(event){
event.dataTransfer.setData("text", event.target.id);
}
function drop(event){
event.preventDefault();
let element = document.getElementById(event.dataTransfer.getData("text"));
event.target.appendChild(element);
element.ondragover = null;
element.ondragover = voidFunc;
element.ondrop = null;
element.ondrop = voidFunc;
}
function allowDrop(event){
event.preventDefault();
}
for(x of document.getElementsByClassName("dragCard")){
x.addEventListener("dragstart", dragStart);
}
for(x of document.getElementsByClassName("drag2")){
x.addEventListener("dragover", allowDrop);
x.addEventListener("drop", drop);
}
and also some CSS:
.dragWrapper{
display: flex;
flex-direction: row;
justify-content: space-around;
}
.drag{
border: 4px dashed black;
width: 200px;
border-radius: 40px;
}
.dragCard{
border: 2px solid black;
border-radius: 10px;
padding: 10px;
margin-left: auto;
margin-right: auto;
margin-top: 10px;
font-size: 20px;
font-weight: 900;
cursor: move;
width: min-content;
color: white;
}
.dragRed{
background-color: red;
}
.dragBlue{
background-color: blue;
}
.dragGreen{
background-color: green;
}
.dragHeader{
font-weight: 600;
margin-bottom: 50px;
}
.dragBase{
border: 2px dotted black;
border-radius: 10px;
}
Is there any way to do this, really? Also, getEventListeners doesn't work for some reason.
I also tried using a different div as a "sensor", so when I drop my cards in them, they would appear in a different div. For this I need to set the sensor zone's z-index and putting it on top of the other div (where the card should end up). I'm working on this right now.