JSFiddle - React, Tailwind, and code Playground
by Thanos Saringelos
HTML
<div id="snapDiv"></div>
CSS
body {
margin: 0;
overflow: hidden;
}
#snapDiv {
width: 100px;
height: 100px;
background-color: lightblue;
position: absolute;
cursor: pointer;
top: 50px;
left: 50px;
}
JavaScript
window.onload = function() {
const snapDiv = document.getElementById('snapDiv');
let isDragging = false;
let offsetX, offsetY;
snapDiv.addEventListener('mousedown', (e) => {
isDragging = true;
offsetX = e.clientX - snapDiv.offsetLeft;
offsetY = e.clientY - snapDiv.offsetTop;
console.log(offsetX);
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
document.addEventListener('mousemove', (e) => {
if (isDragging) {
let newLeft = e.clientX - offsetX;
let newTop = e.clientY - offsetY;
// Snapping logic to the left edge only
if (newLeft <= 10) {
newLeft = 0;
}
snapDiv.style.left = newLeft + 'px';
snapDiv.style.top = newTop + 'px';
}
});
}