Back to the lesson

Drag superheroes around the field

importance: 5

This task can help you to check understanding of several aspects of Drag’n’Drop and DOM.

Make all elements with class draggable – draggable. Like a ball in the chapter.


  • Use event delegation to track drag start: a single event handler on document for mousedown.
  • If elements are dragged to top/bottom window edges – the page scrolls up/down to allow further dragging.
  • There is no horizontal scroll.
  • Draggable elements should never leave the window, even after swift mouse moves.

The demo is too big to fit it here, so here’s the link.

Demo in new window

Open the sandbox for the task.

To drag the element we can use position:fixed, it makes coordinates easier to manage. At the end we should switch it back to position:absolute.

Then, when coordinates are at window top/bottom, we use window.scrollTo to scroll it.

More details in the code, in comments.

Open the solution in the sandbox.