Skip to content

Instantly share code, notes, and snippets.

@SiddharthShyniben
Created November 24, 2021 06:50
Show Gist options
  • Save SiddharthShyniben/cd35cf13929e93b4210ffae72b57f986 to your computer and use it in GitHub Desktop.
Save SiddharthShyniben/cd35cf13929e93b4210ffae72b57f986 to your computer and use it in GitHub Desktop.
Drag and Drop API
<div class="drop">
<div id="drag" draggable="true" ondragstart="event.dataTransfer.setData('text/plain', null)">
Drag me!
</div>
</div>
<div class="drop"></div>
<div class="drop"></div>
<div class="drop"></div>
let dragged;
let listen = (...args) => document.addEventListener(...args);
listen('dragstart', event => {
dragged = event.target;
event.target.style.opacity = 0.5;
event.target.style.transform = 'rotate(-2deg)';
setTimeout(() => event.target.style.transform = '', 1);
}, false)
listen('dragend', event => event.target.style.opacity = '', false)
listen('dragover', event => event.preventDefault(), false);
listen('dragenter', event => {
if (event.target.className === 'drop') event.target.style.background = '#2c41cc';
}, false)
listen('dragleave', event => {
if (event.target.className === 'drop') event.target.style.background = '';
}, false)
listen('drop', event => {
event.preventDefault();
if (event.target.className === 'drop') {
event.target.style.background = '';
dragged.parentNode.removeChild(dragged);
event.target.appendChild(dragged);
}
}, false)
* {
box-sizing: border-box;
font-family: sans-serif;
}
#drag {
width: 200px;
height: 25px;
border-radius: 3px;
background: black;
color: white;
display: grid;
align-items: center;
justify-content: center;
}
.drop {
width: 220px;
height: 45px;
background: #2563EB;
margin-bottom: 10px;
padding: 10px;
border-radius: 3px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment