--- title: Scatter summary: Drag and drop letters around updatedAt: 1717543016000 --- 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: ```js let draggingWindow = undefined; document.addEventListener("mouseup", () => { draggingWindow = undefined }) document.addEventListener("mousemove", (event) => { if(draggingWindow) { draggingWindow.style.setProperty('position', 'absolute') if (event.clientX > 0 && event.clientY > 0) { draggingWindow.style.setProperty('top', `${event.clientY + window.pageYOffset}px`) draggingWindow.style.setProperty('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](https://pfy.ch/rnd/scatter.html).