One of my favorite things about programming is that you almost always end up finding a better, more efficient way of accomplishing something. This means that you are always learning and always becoming better and what you do.
In the past, I have experimented with drag-and-drop, but never really needed to implement it in a large scale. I relied heavily on libraries and workarounds for very simple drag-and-drop tasks because I really didn’t understand it.
Recently, I revisited the HTML5 Drag and Drop API and gained a new understanding/perspective.
I was able to break down the process into some simple steps: make elements “draggable” in the HTML; add “ondragstart” and “ondragend” event handlers to the element being dragged; and add “ondragenter”, “ondragleave” “ondragover”, and “ondrop” event handlers to the element(s) things are being dragged over or dropped onto.
Using this basic idea, I recreated a faux Windows 95 desktop with the simple function of having folders that can be dragged and dropped into a recycle bin. We are all so used to this type of functionality, that it is easy to miss how many things come into play — something that I gained new insight on during this project.
When dragging a folder, it’s opacity is changed to show that it is actively being targeted. Then, when the mouse (still holding the folder) moves over the Recycle Bin, the text highlight changes to show the user they now have the option to do something with the folder and the Recycle Bin. If the user drops the folder outside of the Recycle Bin, the opacity returns to normal; if they drop it on the Recycle Bin, the folder is hidden or removed, the Recycle Bin changes to show that it is full, and the text highlight returns to normal to indicate that the action is complete.
UPDATE: I realized that I wasn’t actually removing the folder elements when dragging them into the Recycle Bin, I was just changing the opacity to 0%. This still allowed for the (now invisible) element to be dragged. I’ve since updated the code to remove the element completely.
I also found that the folders couldn’t be dragged in Firefox. Thanks to the information found here, I was able to resolve this by using the setData method of the dataTransfer object.