Created
January 7, 2020 23:52
-
-
Save tripolskypetr/437619641bd47253a763afdd582a87ef to your computer and use it in GitHub Desktop.
Multi-draggable
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> | |
<title>Drag and drop</title> | |
<style> | |
.ball { | |
width: 200px; | |
height: 200px; | |
position: absolute; | |
} | |
.ball:nth-child(1) { background-color: #465bfa; } | |
.ball:nth-child(2) { background-color: #fa46be; } | |
.ball:nth-child(3) { background-color: #fabb46; } | |
.ball.moving { border: 1px solid black; } | |
</style> | |
</head> | |
<body> | |
<div class="ball"></div> | |
<div class="ball"></div> | |
<div class="ball"></div> | |
<script> | |
document.querySelectorAll('.ball').forEach((ball) => { | |
ball.addEventListener('mouseup', () => ball.classList.remove('moving')); | |
ball.addEventListener('mousedown', () => ball.classList.add('moving')); | |
ball.onmousemove = (e) => | |
[ball.style.top, ball.style.left] = ball.classList.contains('moving') ? [ | |
`${e.pageY - ball.offsetHeight / 2}px`, | |
`${e.pageX - ball.offsetWidth / 2}px`, | |
] : [ball.style.top, ball.style.left]; | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment