MoreLesson 274Free preview
Draggable HTML Element
This lesson is part of How To · All levels
Summary
HTML elements can be made to be moved with an event pointer. When the pointer is pressed, record the starting position of the element and the pointer, then update the position of the element as the pointer moves. Use pointer capture to keep the movement tracked even when the cursor is out of the element, and provide an alternative keyboard.
Key points
- Pointerdown starts the drag process, pointermove updates the position, pointerup ends.
- GetBoundingClientRect() gives the position and size of the element relative to the viewport.
- The elements that are moved usually use positions: absolute or fixed.
- The PointerCapture set ensures that the event pointer remains received during drag.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.