I’ve always been curious about how element dragging is implemented in Javascript. I’ve always just used a library for it.
Work was a little slow so in my free time I whipped up a basic demo for dragging divs around. I realised my demo really did look a bit creepy with letters and words being dragged, so I lent fully into it and made it look like a ransom letter!
It randomises the font-size
, font-family
and rotation
on init.
It’s a little funky with webpage resizes and the code around ensuring the parent takes up set space is inefficient but for a little demo I really don’t mind!
Here’s my three handlers:
let draggingWindow = undefined;
document.addEventListener("mouseup", () => {
= undefined
draggingWindow
})
document.addEventListener("mousemove", (event) => {
if(draggingWindow) {
.style.setProperty('position', 'absolute')
draggingWindowif (event.clientX > 0 && event.clientY > 0) {
.style.setProperty('top', `${event.clientY + window.pageYOffset}px`)
draggingWindow.style.setProperty('left', `${event.clientX + window.pageXOffset}px`)
draggingWindow
}
}
})
// Add an event listener to each of your components you want draggable
// In the demo this is attached in a loop which generates the letters
const draggable = document.getElementsByClassName("scatter")
.addEventListener("mousedown", () => {
draggable= draggable
draggingWindow })
You can check the demo out here.