How to use HTML5 draggable in your game

How to use HTML5 draggable in your game

Drag and drop is the way to go!

Some context

I recently published Barbarians! in itch.io, as I explained on a previous post ✍. It was clear to me that the Game UI 🖥 needed a lot of work (I created that interface 4 years ago and I haven’t really updated it since then).

“Improving UI” is quite a broad concept that includes a lot of small tasks that I have been recording for quite a long time 📋, so I decided to organize this “sub-project” using a GitHub project board. That way I could stay focused on my main goal and don’t get distracted fixing game logic bugs 🐛 for example.

I was reading an article about draggable and I realized that it wasn’t really difficult to implement nowadays with vanilla js 👍🏼. So I created a specific issue for applying this to adding a new feature that would allow users to move their soldiers by dragging them 👆🏾, in addition to the previous moving option of clicking the soldiers and after that clicking the destination 🥱.

barbarians_drag1.gif

What do you need to use draggable

1 - 👆 The HTML draggable attribute

1 - 📨 The dragstart event. Save the id of the node that you are "dragging" in the event data for future use.

2- 📩´The drop and dragover events. On the drop event handler, get the node using the id that you previously saved on the event and then append that node as a child from the event target node (the final node where you dragged the original node), On the dragover event handler, we will just disable the default behavior, as only want to "move" the node when the user releases the click, not only when entering a dragging area.

3 - ❕ Be aware that html attributes and js listener API are different. Do not get confused with the different named events!

How to test it using Cypress

As I explained in a previous post, I use Cypress 🌳 for functionally testing this game. Having to play manually through the same levels over and over is horrible; better to have all the game main features automatically testable ⚙.

After trying simulating mouse 🖱 events by myself using X and Y coordinates with no luck 😢, I found a small library that implements an easy drag feature in cypress. It worked perfectly for my needs because I only needed to use selectors instead of mouse positions 📊. Big thanks and shout-out to the creators, 4teamwork!

Closing words

You can check the full Pull Request if you want more details 😉.

And that's all for today. Personally, I like how easy is to implement a draggable feature without using any framework or libraries; but what do you think 🤗?