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", () => {
  draggingWindow = undefined

document.addEventListener("mousemove", (event) => {
  if(draggingWindow) {'position', 'absolute')
    if (event.clientX > 0 && event.clientY > 0) {'top', `${event.clientY + window.pageYOffset}px`)'left', `${event.clientX + window.pageXOffset}px`)

// 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")
draggable.addEventListener("mousedown", () => {
  draggingWindow = draggable

You can check the demo out here.

© 2024 Pfych 🏳️‍⚧️