This short tutorial will teach you how to build a simple drag-and-drop game using the HTML5 API. The codepen is here.
The DnD behavior is native in HTML5, so you can use the API instead of trying to find workarounds with jQuery or so.
Let’s start with the big picture: in any drag-and-drop application, you’ll have draggable elements, like the pictures above, and drop areas or drop zones. In this game, we have two types of drop areas:
Any element of the page can become draggable by simply adding an attribute to the HTML code, like below:
<img id="cat" src="https://www.veterinarypracticenews.com/wp-content/uploads/2019/10/bigstock-Four-Kittens-On-A-White-Backgr-2730282.jpg" draggable="true" ondragstart="drag(event)" width="300">
Note that the cat picture has an attribute called draggable
which is set to true
.
Now, in order to enable a behavior when we start dragging an element, we need to add an event listener on the draggable node.
The DnD API allows, among others, the following events:
ondragstart
- this event fires when you start dragging the elementondragend
- this event fires when the drag action is completeondragenter
- this event fires when the draggable element is moved into a drop areaondragover
- this event fires when you drag an element over a drop areaondragleave
- this is the opposite of ondragenter
, and fires when the draggable element is pulled out of the drop areaondrop
- this event fires when you drop the element into the drop areaThe first two apply to the draggable element, while the last four concern the drop zone.
So here’s how you need to think when creating this game. First, you need to make an element draggable. I’ve shown how to do this above.
#coding #programming #html #javascript #web-development #scss