Drag and Drop: Drag events

The events we can interact with on the draggable element are:

  • dragstart
  • drag
  • dragend

On the drop target:

  • dragenter
  • dragover
  • dragleave
  • drop

Overview of a drag and drop operation and the events fired

When the user starts dragging a draggable element, clicking on it with the mouse and moving the mourse, or also tapping and keeping the tap and then moving the selection, the dragstart event is fired on it:

element.addEventListener('dragstart', event => {
  //...
})

The event object passed as parameter to the event handling function is a DragEvent object.

It extends from the more general Event object, shared with all the other events: mouse, keyboard, scrolling, etc.

At this point, the element is being dragged, and the drag event is fired. Multiple times as the item is being dragged, so we must use throttling like for the scroll or mouseover events.

As soon as we enter a drop target:

  1. the dragenter event is fired on the drop target
  2. the dragover event is fired on the drop target

If a dragged element first enters a drop target and then moves away from it, the dragleave event is fired on the drop target.

If the user releases the mouse, the dragend event is fired on the element that is being dragged, and a drop event is fired on the drop target.

Lessons in this unit:

0: Introduction
1: Drop targets
2: ▶︎ Drag events
3: Dragging data
4: Set / get the effect
5: The data being transferred
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!