I am just starting to learn JavaScript and I was doing some examples of drag & Drop that work very well and easily for paragraphs, but I am having some issues with dropping images. I have created an image inside a div, and another empty div where I want to place the image, for some reason, the image moves for a short time, but then... my image becomes my whole HTML, replacing everything else.
I would like just to move the image to the empty square I created.
THANKS IN ADVANCE :)
My HTML looks like this:
<div class="container">
<div id="12" class="imagen-div">
<img src="img-2.jpg" alt="row-1-column-2" class="imagen" draggable="true">
</div>
</div>
<div class="empty-container">
<div id="e11" class="empty"></div>
</div>
</div>
And my JS:
const imagenes = document.querySelectorAll(".imagen-div")
const vacios = document.querySelectorAll(".empty")
imagenes.forEach(imagen => {
imagen.addEventListener("dragstart", event => {
imagen.classList.add("dragging")
event.dataTransfer.setData("id", imagen.id)
})
imagen.addEventListener("dragend", () => {
imagen.classList.remove("dragging")
})
})
vacios.forEach(vacio => {
vacio.addEventListener("dragover", event => {
event.preventDefault()
event.dataTransfer.dropEffect = "move"
})
vacio.addEventListener("drop", event => {
const id_imagen = event.dataTransfer.getData("id")
const imagen = document.getElementById(id_imagen)
vacio.appendChild(imagen)
})
})
And I gave some style with CSS:
.imagen {
width: 10rem;
}
.empty {
width: 10rem;
height: 10rem;
border: 1px solid #bbbb;
}