Sifting the Drag and Drop API

Ian Gornall
DigitalCrafts
Published in
2 min readAug 27, 2018

The most appealing tourist traps to me as a kid were gold and gem mines. Sift for gold! Hidden treasure in a pile of dirt. I was a gullible kid, and hearing other people talk about the nuggets they found worth thousands, I never doubted them for a second. I never found a thing.

Reading documentation is sometimes just like sifting for gold. All I see is a pile of dirt.

Recently, I was on a team trying to implement drag and drop using the built in web API. The documentation begins with a very enticing intro, “with these features, the user can select draggable elements with a mouse, drag the elements to a droppable element, and drop those elements by releasing the mouse button.” Make an element draggable and another droppable and you have drag and drop? Easy gold.

Turns out that little intro: Pyrite, fool’s gold. It quickly turns to a description of eight event listeners. Then, the documentation goes on to describe four “interfaces.” Interfaces? Event Listeners?

The intro made it seem like a matter of setting two attributes, draggable and droppable. In fact, there is one attribute, draggable, and it turns out, that does very little on its own.

Maybe the fact that there are enough drag and drop libraries to fill a post about the best 10 should have indicated it would require some work to implement. On the other hand, their existence reassured me that the gold existed.

Reading does not alone let you find gold. It requires experimentation. At least for me.

A member of the dev team, Nat Sharpe, helped by providing some sample code. Sample code is tricky to work with as a learning tool. You can easily just copy and paste it, modify it for your use, and move on. This is not helpful to developing understanding.

My approach was to take the code and copy over only the bare minimum that I thought was necessary, checking the documentation to be sure I knew what each piece was doing. In this case, I was able to use reduce what I needed down to 15 lines of code that allow you to drop an element back and forth between containers:

Sifting

This method of finding minimal sample code, stripping it further down, and referencing documentation allowed me to sift through a bunch of information and find gold. Drag and drop functionality that I understood.

Bonus: polyfill (makes it work on mobile): https://github.com/Bernardo-Castilho/dragdroptouch/blob/master/DragDropTouch.js

--

--

Ian Gornall
DigitalCrafts

www.iangornall.com | Hi, I am a software engineer at Digital Crafts. I write about the joys of code.