A simple implementation of drag-and-drop using XState. Based on this video by Fun Fun Function (R.I.P.). It adds some extra functionality, though:
- Supports multiple draggable elements
- Re-orders the z-index attribute based on the last dragged element
- Nice animations for dragged elements
You can preview the final result on this project's GitHub pages.
The basic idea is:
- Add event listeners on the
document
formousedown
,mousemove
andmouseup
events. - Delegate
mousedown
events for targets with both an id and thedata-draggable
custom attribute to XState. - XState saves a reference to the target element, and creates an entry on the context value
draggables
if it doesn't have one. - On
mouseMove
, we move set the element'stop
andleft
style attributes based on the current mouse position + the initial element position onmousedown
. - On
mousedown
, we persist the dragged element's position on ourdraggables
Map.
This project uses Parcel for bundling. Clone this repository, open the folder on terminal and run npm start
. Parcel will give you a nice local server that will watch and reload for every change you make.
To build the project, run the build
npm script using the command npm run build
. The build will be found on the docs directory. Simple as that! ✨
If you have any questions about the code, the project, life or anything else, you can contact-me via e-mail or twitter.