Skip to content

Instantly share code, notes, and snippets.

@laziel laziel/draggable.js
Created Jul 3, 2018

Embed
What would you like to do?
Pure JavaScript Draggable
(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);
})();
<!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>
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
You can’t perform that action at this time.