const windowElement = document.getElementById('window'); let isDragging = false; let initialX; let initialY; windowElement.addEventListener('mousedown', startDragging); windowElement.addEventListener('mouseup', stopDragging); windowElement.addEventListener('mousemove', drag); function startDragging(e) { isDragging = true; initialX = e.clientX - windowElement.getBoundingClientRect().left; initialY = e.clientY - windowElement.getBoundingClientRect().top; } function stopDragging() { isDragging = false; } function drag(e) { if (isDragging) { const newX = e.clientX - initialX; const newY = e.clientY - initialY; windowElement.style.left = `${newX}px`; windowElement.style.top = `${newY}px`; } } body { font-family: Arial, sans-serif; margin: 0; padding: 0; } .window { position: absolute; width: 300px; height: 200px; background-color: #f0f0f0; border: 1px solid #ccc; box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3); cursor: move; }
Drag me!
This is a movable floating window.