JSFiddle - React, Tailwind, and code Playground
HTML
<div class="guide-line"></div>
<div style="height:500px; width:500px;background-color:green;">
<div id="drag-container">
<div id="dragger">Drag</div>
</div>
</div>
CSS
body {
font-family: Arial, sans-serif;
}
#dragger {
position: absolute;
left: 100px;
padding: 10px;
width: 40px;
color: white;
cursor: move;
background:red;
}
#drag-container {
position: relative;
width: 100px;
height: 100%;
background: orange;
z-index:2;
}
.guide-line {
position: absolute;
width: 100px;
height: 100%;
border-right: 1px solid gray;
z-index: 10;
}
JavaScript
window.onload = addListeners();
var xPosition = 0;
function addListeners() {
document.getElementById('drag-container').addEventListener("click", getClickPosition, false);
document.getElementById('dragger').addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);
}
function getClickPosition(e) {
xPosition = e.clientX;
console.log(xPosition);
}
function mouseUp() {
window.removeEventListener('mousemove', divMove, true);
}
function mouseDown(e) {
window.addEventListener('mousemove', divMove, true);
}
function divMove(e) {
var max = 443;
var x = event.clientX;
var div = document.getElementById('dragger');
var offset = div.offsetWidth/2;
if (x > (100 + offset) && x < (max+offset)) {
div.style.position = 'absolute';
div.x = xPosition;
div.style.left = (e.clientX - offset) + 'px';
}
//console.log(x);
}