Skip to content

Instantly share code, notes, and snippets.

@rumbis
Created August 9, 2022 21:17
Show Gist options
  • Save rumbis/c0567e645bd57ce6e135ead0fec1b0a7 to your computer and use it in GitHub Desktop.
Save rumbis/c0567e645bd57ce6e135ead0fec1b0a7 to your computer and use it in GitHub Desktop.
Drag & Drop - Vanilla JavaScript
<div class="empty">
<div class="fill" draggable="true"> </div>
</div>
<div class="empty">
</div>
<div class="empty">
</div>
<div class="empty">
</div>
<div class="empty">
</div>
const fill = document.querySelector('.fill');
const empties = document.querySelectorAll('.empty');
// Fill listeners
fill.addEventListener('dragstart', dragStart);
fill.addEventListener('dragend', dragEnd);
// Loop through empty boxes and add listeners
for (const empty of empties) {
empty.addEventListener('dragover', dragOver);
empty.addEventListener('dragenter', dragEnter);
empty.addEventListener('dragleave', dragLeave);
empty.addEventListener('drop', dragDrop);
}
// Drag Functions
function dragStart() {
this.className += ' hold';
setTimeout(() => (this.className = 'invisible'), 0);
}
function dragEnd() {
this.className = 'fill';
}
function dragOver(e) {
e.preventDefault();
}
function dragEnter(e) {
e.preventDefault();
this.className += ' hovered';
}
function dragLeave() {
this.className = 'empty';
}
function dragDrop() {
this.className = 'empty';
this.append(fill);
}
body {
background: white;
display:flex;
flex-direction:column;
justify-content:center;
align-items:center;
}
.fill {
background-image: url('https://source.unsplash.com/random/160x160');
position: relative;
height: 160px;
width: 160px;
cursor: pointer;
}
.hold {
border: solid 5px #ccc;
}
.empty {
height: 160px;
width: 160px;
margin: 10px;
border: solid 3px salmon;
border-radius:1px;
background: white;
}
.hovered {
background: #f4f4f4;
border-style: dashed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment