Created
July 3, 2018 08:37
-
-
Save laziel/45b291288ee066ac219992ac8d0a2c24 to your computer and use it in GitHub Desktop.
Pure JavaScript 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
(function () { | |
const wrapper = document.querySelector(`#test`); | |
const pos = {}; | |
const moveDrag = evt => { | |
// const { scrollLeft, scrollTop } = document.scrollingElement; | |
const o = { | |
top: wrapper.offsetTop - (pos.clientY - evt.clientY), | |
left: wrapper.offsetLeft - (pos.clientX - evt.clientX) | |
}; | |
pos.clientX = evt.clientX; | |
pos.clientY = evt.clientY; | |
wrapper.style.top = `${o.top}px`; | |
wrapper.style.left = `${o.left}px`; | |
// console.log(o); | |
}; | |
const endDrag = () => { | |
wrapper.dataset.dragging = ``; | |
window.removeEventListener(`mousemove`, moveDrag); | |
window.removeEventListener(`mouseup`, endDrag); | |
window.removeEventListener(`mouseleave`, endDrag); | |
}; | |
const startDrag = evt => { | |
if (wrapper.dataset.dragging === `true`) { | |
return; | |
} | |
wrapper.dataset.dragging = `true`; | |
window.addEventListener(`mousemove`, moveDrag); | |
window.addEventListener(`mouseup`, endDrag); | |
window.addEventListener(`mouseleave`, endDrag); | |
pos.clientX = evt.clientX; | |
pos.clientY = evt.clientY; | |
}; | |
wrapper.addEventListener(`mousedown`, startDrag); | |
})(); |
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 name="viewport" content="width=device-width"> | |
<title>DRAG</title> | |
<link href="style.css" rel="stylesheet"> | |
</head> | |
<body> | |
<div id="test">TRY DRAG ME</div> | |
<script src="draggable.js"></script> | |
</body> | |
</html> |
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
body { | |
width: 3000px; | |
height: 3000px; | |
} | |
#test { | |
position: absolute; | |
top: 150px; | |
left: 582px; | |
background: #efefef; | |
border: 1px solid #ddd; | |
border-radius: 5px; | |
width: 150px; | |
height: 30px; | |
cursor: move; | |
text-align: center; | |
font-size: 15px; | |
font-weight: bold; | |
display: flex; | |
align-items: center; | |
justify-content: center; | |
user-select: none; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment