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:

  • the boxes at the top, which contain the animal names
  • the container at the bottom, where the animal images are at the beginning

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 element
  • ondragend - this event fires when the drag action is complete
  • ondragenter - this event fires when the draggable element is moved into a drop area
  • ondragover - this event fires when you drag an element over a drop area
  • ondragleave - this is the opposite of ondragenter, and fires when the draggable element is pulled out of the drop area
  • ondrop - this event fires when you drop the element into the drop area

The 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

Beginner Drag-and-Drop Game with HTML, SCSS and JS
25.75 GEEK