Skip to content

Instantly share code, notes, and snippets.

@alekstar79
Last active May 24, 2024 16:57
Show Gist options
  • Save alekstar79/00303825f7d42476e2ee to your computer and use it in GitHub Desktop.
Save alekstar79/00303825f7d42476e2ee to your computer and use it in GitHub Desktop.
Draggable
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Draggable</title>
<style>
.draggable {
position: absolute;
width: 80px;
height: 60px;
padding-top: 10px;
text-align: center;
font-size: 40px;
background-color: #222;
color: #CCC;
cursor: move;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
</style>
</head>
<body>
<div class="draggable">1</div>
<div class="draggable">2</div>
<div class="draggable">3</div>
<script>
;(function() {
let elements = document.getElementsByTagName('div'),
elementsLength = elements.length,
storage = {}
for (var i = 0; i < elementsLength; i++) {
if (elements[i].className === 'draggable') {
elements[i].addEventListener('mousedown', function(e) {
storage.target = e.target
storage.offsetX = e.clientX - storage.target.offsetLeft
storage.offsetY = e.clientY - storage.target.offsetTop
}, false)
elements[i].addEventListener('mouseup', function() {
storage = {}
}, false)
}
}
document.addEventListener('mousemove', function(e) {
let target = storage.target
if (target) {
target.style.top = e.clientY - storage.offsetY + 'px'
target.style.left = e.clientX - storage.offsetX + 'px'
}
}, false)
})()
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment