I've set up draggable divs that allow users to drag categories of data over to a table. Due to the nature of the data, we need to give users a signal of where the data can be dropped.
I'd like to add a "highlight" class to specific divs elsewhere on the page that will show users where these categories of data can be dropped.
The following code adds the new class to the divs correctly, but when the draggable div is dropped without completing the drag, the class is not removed. I feel like I'm missing something simple.
<script>
var columnsDrop = document.getElementById("columnsDrop");
var rowsDrop = document.getElementById("rowsDrop");
var filtersDrop = document.getElementById("filtersDrop");
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
columnsDrop.classList.add("highlight");
rowsDrop.classList.add("highlight");
filtersDrop.classList.add("highlight");
}
function drop(ev) {
ev.target.appendChild(document.getElementById(data));
columnsDrop.classList.remove("highlight");
rowsDrop.classList.remove("highlight");
filtersDrop.classList.remove("highlight");
}
</script>
I was able to work this out on my own with some experimentation and additional reading.
<script>
const pill = document.querySelector('.filters__pill');
const dropIcons = document.querySelectorAll('.drop__icon');
pill.addEventListener('dragstart', dragStart);
pill.addEventListener('dragend', dragEnd);
dropIcons.forEach(i => {
i.addEventListener('dragenter', dragEnter)
i.addEventListener('dragover', dragOver);
i.addEventListener('dragleave', dragLeave);
i.addEventListener('drop', drop);
});
function dragStart() {
dropIcons.forEach(i => {
i.classList.remove('disabled');
i.classList.remove('hidden');
});
pills.forEach(p => {
p.classList.add('disabled');
});
}
function dragEnd() {
dropIcons.forEach(i => {
i.classList.add('disabled');
i.classList.add('hidden');
});
pills.forEach(p => {
p.classList.remove('disabled');
});
}
</script>