Building a movable and adjustable popup dialog with vanilla JavaScript

I’m working on a web project where I need to implement a modal dialog that users can drag around the screen and resize as needed. The tricky part is that I want this to work consistently across different browsers like Chrome, Firefox, Safari, and Edge.

I’ve been trying to figure out the best approach to handle mouse events for dragging functionality and corner/edge detection for resizing. I’m particularly concerned about how to manage the cursor changes when hovering over resize areas and how to properly calculate the new dimensions during resize operations.

Since I prefer to keep my project lightweight, I’d rather not include heavy libraries like jQuery UI or similar frameworks. Does anyone have experience implementing this kind of functionality using pure JavaScript? Any tips on handling the event listeners and DOM manipulation would be really helpful.

I’ve started with basic mouse down and move events but I’m struggling with the resize logic and making sure everything works smoothly across different browsers.

I built something like this last year. The tricky part isn’t dragging - it’s stopping text selection while you drag. Add user-select: none to your dialog CSS and call event.preventDefault() on mousedown. That’ll stop the browser from selecting text.

For resizing, create invisible handles at the corners and edges with absolute positioning. Set their cursors to nw-resize, ne-resize, etc. You’ll need to track mouse position and the dialog’s original size to calculate new dimensions.

One gotcha: mouse events can fire outside the dialog during fast movements. I fixed this by attaching mousemove and mouseup listeners to the document instead of just the dialog element. Also set minimum width/height so users can’t make it unusably tiny.

Resize detection zones were a nightmare when I built this. Skip invisible handles - just check mouse coords against dialog boundaries. Make an 8-10px buffer around each edge and change cursor styles there. On mousemove, figure out which zone you’re in and update cursor. For resize math, track direction on mousedown - top, bottom, left, right, or corners. While dragging, only change what you need. Bottom-right corner? Just bump width/height. Top-left gets messy since you’re adjusting position AND size together. Throttle your mousemove handler or it’ll be janky on slower devices. I used requestAnimationFrame to batch DOM updates.

Cross-browser stuff is annoying but I’ve done this before. Use setCapture() for IE compatibility if you still care about that. Watch out for resize calculations - store the starting mouse position AND the dialog’s initial dimensions when mousedown happens, then calculate the difference on mousemove. Add bounds checking so users can’t drag it completely offscreen.

This topic was automatically closed 6 hours after the last reply. New replies are no longer allowed.