I have been working on incorporating this code snippet from Web Dev Simplified into my project:
JS:
const draggables = document.querySelectorAll('.draggable')
const containers = document.querySelectorAll('.drag-container')
draggables.forEach(draggable => {
draggable.addEventListener('dragstart', () => {
draggable.classList.add('dragging')
})
draggable.addEventListener('dragend', () => {
draggable.classList.remove('dragging')
})
})
containers.forEach(container => {
container.addEventListener('dragover', e => {
e.preventDefault()
const afterElement = getDragAfterElement(container, e.clientY)
const draggable = document.querySelector('.dragging')
if (afterElement == null) {
container.appendChild(draggable)
} else {
container.insertBefore(draggable, afterElement)
}
})
})
function getDragAfterElement(container, y) {
const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')]
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect()
const offset = y - box.top - box.height / 2
if (offset < 0 && offset > closest.offset) {
return { offset: offset, element: child }
} else {
return closest
}
}, { offset: Number.NEGATIVE_INFINITY }).element
}
CSS:
.drag-container {
background-color: #333;
padding: 1rem;
margin-top: 1rem;
}
.draggable {
padding: 1rem;
background-color: white;
border: 1px solid black;
cursor: move;
}
.draggable.dragging {
opacity: .5;
}
Despite spending most of my time with C# for the backend, I decided to try out some frontend JS by implementing the above code. However, I'm facing issues as it doesn't seem to work seamlessly with my existing code that previews images before uploading:
function previewImages() {
let aux = document.getElementById("preview-multiple");
if (aux.hasChildNodes()) {
while (aux.firstChild) {
aux.removeChild(aux.firstChild);
}
}
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
}
var div = document.createElement('div');
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
image.className = "draggable";
image.draggable = true;
//draggable.js dependent of previewImage.js
aux.appendChild(div);
div.appendChild(image)
});
reader.readAsDataURL(file);
}
}
In my image preview code, I specifically added:
image.className = "draggable";
image.draggable = true;
to enable dragging functionality and organized them within divs for better structure.
However, encountering errors when attempting to drag the images has left me baffled:
https://i.sstatic.net/tXJJF.png
I am unsure where I may be going wrong in my implementation.
My next challenge includes saving these images in a database with ordering based on the View, but that's a task for another day.
Do you have any insights or solutions to offer? Thank you.