Exercise – creating a drag-and-drop event
A drag-and-drop behavior means clicking on an element, moving the mouse while holding down the click to drag the element across the screen to the desired location, and then releasing the mouse click to drop the element in the new location.
A drag-and-drop behavior thus involves coordination between multiple events, namely, 'mousedown'
, 'mousemove'
, and 'mouseup'
.
As we perform the drag-and-drop motion, what we are interested in knowing is when the dragging starts, how far the element is dragged, and when the dragging ends.
These three events can be translated into three custom events: 'dragStart'
, 'dragMove'
, and 'dragEnd'
.
Let us try to implement the drag-and-drop behavior as an action that will create these three custom events:
<div use:dragAndDrop on:dragStart={...} on:dragMove={...} on:dragEnd={...} />...