Created
September 1, 2018 09:27
-
-
Save cagcak/073d26e4714cf35a6b79ba6507dca248 to your computer and use it in GitHub Desktop.
Simple Drag and Drop application in Vanilla JS by TraversyMedia
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<title></title> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<style> | |
body { | |
background-color: darkgrey; | |
} | |
.fill { | |
background-image: url('http://source.unsplash.com/random/150x150'); | |
position: relative; | |
height: 150px; | |
width: 150px; | |
top: 5px; | |
left: 5px; | |
cursor: pointer; | |
} | |
.empty { | |
display: inline-block; | |
height: 160px; | |
width: 160px; | |
margin: 10px; | |
border: 3px salmon solid; | |
background-color: aliceblue; | |
} | |
.hold { | |
border: solid #ccc 4px; | |
} | |
.hovered { | |
background: #f4f4f4; | |
border-style: dashed; | |
} | |
.invisible { | |
display: none; | |
} | |
</style> | |
</head> | |
<body> | |
<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> | |
<script> | |
const fill = document.querySelector('.fill') | |
const empties = document.querySelectorAll('.empty') | |
// Fill listeners | |
fill.addEventListener('dragstart', dragStart) | |
fill.addEventListener('dragend', dragEnd) | |
// Loop through empties and call drag events | |
for (const empty of empties) { | |
empty.addEventListener('dragover', dragOver) | |
empty.addEventListener('dragenter', dragEnter) | |
empty.addEventListener('dragleave', dragLeave) | |
empty.addEventListener('drop', dragDrop) | |
} | |
function dragStart() { | |
// console.log('drag start') | |
this.className += ' hold' | |
setTimeout(() => (this.className = 'invisable', 0)) | |
} | |
function dragEnd() { | |
// console.log('drag end') | |
this.className = 'fill' | |
} | |
function dragOver (e) { | |
e.preventDefault() | |
// console.log('drag over') | |
} | |
function dragEnter (e) { | |
e.preventDefault() | |
// console.log('drag enter') | |
this.className += ' hovered' | |
} | |
function dragLeave (e) { | |
e.preventDefault() | |
// console.log('drag leave') | |
this.className = 'empty' | |
} | |
function dragDrop (e) { | |
e.preventDefault() | |
// console.log('drag drop') | |
this.className = 'empty' | |
this.append(fill) | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment