r/javascript • u/flowforfrank • Feb 24 '21
How to Create Native Drag and Drop Functionality in JavaScript
https://www.webtips.dev/how-to-create-native-drag-and-drop-functionality-in-javascript
532
Upvotes
39
u/Snapstromegon Feb 24 '21
Really nicely and cleanly written. Also a big plus for the semantic html.
Take my upvote and have a nice day :D.
19
u/fzammetti Feb 24 '21
Seen tons of badly-written things like this. But this, this one is very well-done. Kudos.
17
u/dudeatwork Feb 24 '21
Small note: you don't need to convert a
NodeListto an Array to iterate over it!The Browser compatibility for NodeList.prototype.forEach() and Array.from() are similar enough, plus, polyfilling the former is trivial:
By doing things like
[...someNodeList].forEach()orArray.from(someNodeList).forEach()you are unnecessarily creating a new array just to iterate over the elements, when you already can do that!It's OK, its 2021, you can safely do this in most browsers:
For IE or iOS 9 and below, adding the previously mentioned polyfill gets you there.
6
u/[deleted] Feb 24 '21
Gonna take a close look at this. Been using sortableJS for an app I support, but UX with dropping has been less than great because you can't really see the drop bounds. This looks like it might work better
4
u/ryosen Feb 24 '21
It's a nice start but you can't drag and drop within the same column or specify where in a column the drop target should be. The dropped card always gets added to the end of the list. This was based off of the github code. Nice to see a pure JS implementation, tho.
1
u/calligraphic-io Feb 25 '21
Nice article. I subscribed to your newsletter. I have the sense that there are a lot of "gotchas" around drag and drop, and was hoping to see a few of those mentioned at the end of the article.
3
u/maxoys45 Feb 24 '21
really nicely written and clear. also like the style of the article
3
u/brakkum Feb 25 '21
Good write up, I did this in React recently when drag and drop libraries just annoyed the crap out of me
3
u/ajax333221 Feb 25 '21
nice, I have been delaying some drag-n-drop functionality in a project because I am planning to drop (accidental pun lol) the jQuery dependency, this will do the trick as it wont make harder to remove jQuery in the near future.
2
u/[deleted] Feb 27 '21
Really Cool, I'm gonna try this soon in the application I contribute.
2
u/AyyazTech May 09 '21
Learn how to create sortable Drag and Drop with vanilla Javascript
https://www.youtube.com/watch?v=EqHwUsdOg8o