👀 I have never used drag&drop functionality with vanilla JavaScript.
In the enterprise applications I work on every day, I usually rely on frameworks such as Angular, React, or Vue that provide easier ways to handle it and, in addition, solve the classic problems that I would have to handle by hand.
💡 That's why I wanted to give it a try, developing a very basic project in HTML and JS.
Here, briefly, is what I figured out:
draggable attribute on it.<div class="item" draggable="true">Drag me</div>
dragStart event must be added to it.<div id="my-item" class="item" draggable="true" ondragstart="handleDragStart(event)" > Drag me </div> <script> function handleDragStart(e) { console.log("You are dragging ", e.target.id); } </script>
dragOver and drop events.<div class="dropzone" ondrop="handleDrop(event)" ondragover="handleDragOver(event)" > Drop the dragging element here! </div> <script> function handleDrop(e) { e.preventDefault(); // prevent default action (e.g. open as link for some elements) // CODE HERE (e.g. append element to the drop zone) } function handleDragOver(e) { e.preventDefault(); // Required to allow Drop event } </script>
That's pretty much it!
As usual, I created a stackblitz project where you can use drag&drop to switch placements in a podium and choose which is the best 🏆 framework/library among Angular🥇, Vue🥈, and React🥉! (Try to guess what my ranking is 😁)
And here is the link to the demo if you just want to play with it!
P.S. I did not use the dataTransfer property, but I will create a more "data-driven" demo to explain this function as well in the future.