It looks like I’m a contender for a Ruby on Rails position, and I’ve been tasked with adding some functionality to a skeleton project. One of the requirements is that I implement a “drag and drop” feature that will reorder a list of events with those actions.

I’m going to show you a really simple tool to use called “SortableJs” that will make your life significantly easier.

You’re going to want to do your typical installation and require the file in your javascript/packs/application.js file.

So where the magic comes in, is tying this sortable object to the html it runs on. To do this, we simply add an id field to the block of HTML that is being loaded…

association time!

Next, you’ll want to add some boilerplate code into your application.js file…

The element variable is being assigned to the events-list that we created prior. It uses that element to create a sortable list. Don’t forget to import the dependency at the top of the page with the other required resources. The syntax will need to read like “ import Sortable from ‘sortablejs’ ” .

From here, you have access to a bevy of information and functions in relation to drag and drop. For example, SortableJs comes with a built-in function called “onEnd” which gets triggered once an item has been clicked, dragged, then set. You can even track an items location on a list using attributes like oldIndex and newIndex.

Easy breezy! Down the line I’m going to revisit this, and talk about persisting all that data to the backend. Cheers!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store