Drag & Drop Rails Components
Sortable lists, grids, tabs and dropzones that feel hand-built. The lifted item follows your pointer, neighbours glide out of the way, and the drop settles like a soft spring. Works with mouse, touch and keyboard, and keeps your Rails records in order with hidden inputs, an event, or a PATCH request.
Installation
1. Stimulus Controller Setup
One controller, no dependencies. It uses pointer events and the browser’s Web Animations API instead of the native HTML5 drag and drop, so there is no ghost image and it behaves the same on touch screens.
This code is available to Pro users only.
// Hey curious person!
// You seem to be sneaking around the code...
// I hope you're enjoying the components!
// Have a great day!
class SecretMessage {
constructor() {
this.message = "Thanks for checking out Rails Blocks!";
this.compliment = "You're awesome!";
}
reveal() {
console.log(this.message);
return this.compliment;
}
}
const secret = new SecretMessage();
secret.reveal();
Examples
Basic sortable list
Grab any row and move it. With the keyboard: focus a row, press Space to lift, the arrow keys to move, Space to drop and Esc to cancel.
This code is available to Pro users only.
<!-- Hey curious person! -->
<!-- You seem to be sneaking around the code... -->
<!-- I hope you're enjoying the components! -->
<!-- Have a great day! -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Secret Message from Rails Blocks</title>
<style>
.secret-message {
font-family: 'Comic Sans MS', cursive;
text-align: center;
padding: 2rem;
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.wiggle { animation: wiggle 0.5s ease-in-out infinite; }
@keyframes wiggle {
0%, 100% { transform: rotate(0deg); }
25% { transform: rotate(1deg); }
75% { transform: rotate(-1deg); }
}
</style>
</head>
<body>
<div class="secret-message">
<h1>🎉 Hello, Code Detective! 🕵️</h1>
<p>Thanks for checking out Rails Blocks!</p>
<p>You're clearly someone who pays attention to details.</p>
<p>That's exactly the kind of developer we love!</p>
<div class="cta-section">
<button class="awesome-btn wiggle">You're awesome!</button>
<p><small>Seriously, keep being curious! 🚀</small></p>
</div>
<footer>
<p>Built with ❤️ by the Rails Blocks team</p>
<p>Now go build something amazing!</p>
</footer>
</div>
<script>
console.log("🎊 Bonus points for opening the console!");
console.log("Keep exploring and happy coding! 💻");
</script>
</body>
</html>
With drag handles
Only the handle starts a drag, so switches, links and inputs inside the row stay fully usable. The lifted row is locked to the vertical axis.
Sidebar
Drag the handle to reorder. Toggle to show or hide a link.
This code is available to Pro users only.
<!-- Hey curious person! -->
<!-- You seem to be sneaking around the code... -->
<!-- I hope you're enjoying the components! -->
<!-- Have a great day! -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Secret Message from Rails Blocks</title>
<style>
.secret-message {
font-family: 'Comic Sans MS', cursive;
text-align: center;
padding: 2rem;
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.wiggle { animation: wiggle 0.5s ease-in-out infinite; }
@keyframes wiggle {
0%, 100% { transform: rotate(0deg); }
25% { transform: rotate(1deg); }
75% { transform: rotate(-1deg); }
}
</style>
</head>
<body>
<div class="secret-message">
<h1>🎉 Hello, Code Detective! 🕵️</h1>
<p>Thanks for checking out Rails Blocks!</p>
<p>You're clearly someone who pays attention to details.</p>
<p>That's exactly the kind of developer we love!</p>
<div class="cta-section">
<button class="awesome-btn wiggle">You're awesome!</button>
<p><small>Seriously, keep being curious! 🚀</small></p>
</div>
<footer>
<p>Built with ❤️ by the Rails Blocks team</p>
<p>Now go build something amazing!</p>
</footer>
</div>
<script>
console.log("🎊 Bonus points for opening the console!");
console.log("Keep exploring and happy coding! 💻");
</script>
</body>
</html>
Sortable card grid
The same controller sorts wrapping grids. Cards tilt slightly while lifted and lean into the direction you drag them. With the keyboard, the arrow keys move focus between cards; press Space to pick one up, then the arrow keys carry it across rows and columns and Space drops it.
This code is available to Pro users only.
<!-- Hey curious person! -->
<!-- You seem to be sneaking around the code... -->
<!-- I hope you're enjoying the components! -->
<!-- Have a great day! -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Secret Message from Rails Blocks</title>
<style>
.secret-message {
font-family: 'Comic Sans MS', cursive;
text-align: center;
padding: 2rem;
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.wiggle { animation: wiggle 0.5s ease-in-out infinite; }
@keyframes wiggle {
0%, 100% { transform: rotate(0deg); }
25% { transform: rotate(1deg); }
75% { transform: rotate(-1deg); }
}
</style>
</head>
<body>
<div class="secret-message">
<h1>🎉 Hello, Code Detective! 🕵️</h1>
<p>Thanks for checking out Rails Blocks!</p>
<p>You're clearly someone who pays attention to details.</p>
<p>That's exactly the kind of developer we love!</p>
<div class="cta-section">
<button class="awesome-btn wiggle">You're awesome!</button>
<p><small>Seriously, keep being curious! 🚀</small></p>
</div>
<footer>
<p>Built with ❤️ by the Rails Blocks team</p>
<p>Now go build something amazing!</p>
</footer>
</div>
<script>
console.log("🎊 Bonus points for opening the console!");
console.log("Keep exploring and happy coding! 💻");
</script>
</body>
</html>
Reorderable navigation
The links are the items: click to follow one, drag to reorder it. The strip is locked to its rail like browser tabs, scrolls on its own as you drag towards an edge, and a click right after a drag is swallowed so a drop never navigates.
This code is available to Pro users only.
<!-- Hey curious person! -->
<!-- You seem to be sneaking around the code... -->
<!-- I hope you're enjoying the components! -->
<!-- Have a great day! -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Secret Message from Rails Blocks</title>
<style>
.secret-message {
font-family: 'Comic Sans MS', cursive;
text-align: center;
padding: 2rem;
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.wiggle { animation: wiggle 0.5s ease-in-out infinite; }
@keyframes wiggle {
0%, 100% { transform: rotate(0deg); }
25% { transform: rotate(1deg); }
75% { transform: rotate(-1deg); }
}
</style>
</head>
<body>
<div class="secret-message">
<h1>🎉 Hello, Code Detective! 🕵️</h1>
<p>Thanks for checking out Rails Blocks!</p>
<p>You're clearly someone who pays attention to details.</p>
<p>That's exactly the kind of developer we love!</p>
<div class="cta-section">
<button class="awesome-btn wiggle">You're awesome!</button>
<p><small>Seriously, keep being curious! 🚀</small></p>
</div>
<footer>
<p>Built with ❤️ by the Rails Blocks team</p>
<p>Now go build something amazing!</p>
</footer>
</div>
<script>
console.log("🎊 Bonus points for opening the console!");
console.log("Keep exploring and happy coding! 💻");
</script>
</body>
</html>
Between two lists
Lists inside the same controller are connected. Move table columns between hidden and visible; counts and empty states update as you go. The visible list has data-drag-and-drop-limit="5" with data-drag-and-drop-limit-strict, so a sixth column is refused and the list turns red (data-drag-and-drop-refusing) while you hover it.
Hidden columns
4- Every column is visible
Visible columns
3/5- Drop a column here to show it
This code is available to Pro users only.
<!-- Hey curious person! -->
<!-- You seem to be sneaking around the code... -->
<!-- I hope you're enjoying the components! -->
<!-- Have a great day! -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Secret Message from Rails Blocks</title>
<style>
.secret-message {
font-family: 'Comic Sans MS', cursive;
text-align: center;
padding: 2rem;
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.wiggle { animation: wiggle 0.5s ease-in-out infinite; }
@keyframes wiggle {
0%, 100% { transform: rotate(0deg); }
25% { transform: rotate(1deg); }
75% { transform: rotate(-1deg); }
}
</style>
</head>
<body>
<div class="secret-message">
<h1>🎉 Hello, Code Detective! 🕵️</h1>
<p>Thanks for checking out Rails Blocks!</p>
<p>You're clearly someone who pays attention to details.</p>
<p>That's exactly the kind of developer we love!</p>
<div class="cta-section">
<button class="awesome-btn wiggle">You're awesome!</button>
<p><small>Seriously, keep being curious! 🚀</small></p>
</div>
<footer>
<p>Built with ❤️ by the Rails Blocks team</p>
<p>Now go build something amazing!</p>
</footer>
</div>
<script>
console.log("🎊 Bonus points for opening the console!");
console.log("Keep exploring and happy coding! 💻");
</script>
</body>
</html>
Grouped list
Stacked groups in one card. Drag a task to another day, or keep pressing the down arrow to carry it past the end of one group into the next.
Today 3
- Nothing planned. Drop a task here.
Tomorrow 2
- Nothing planned. Drop a task here.
Later this week 0
- Nothing planned. Drop a task here.
This code is available to Pro users only.
<!-- Hey curious person! -->
<!-- You seem to be sneaking around the code... -->
<!-- I hope you're enjoying the components! -->
<!-- Have a great day! -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Secret Message from Rails Blocks</title>
<style>
.secret-message {
font-family: 'Comic Sans MS', cursive;
text-align: center;
padding: 2rem;
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.wiggle { animation: wiggle 0.5s ease-in-out infinite; }
@keyframes wiggle {
0%, 100% { transform: rotate(0deg); }
25% { transform: rotate(1deg); }
75% { transform: rotate(-1deg); }
}
</style>
</head>
<body>
<div class="secret-message">
<h1>🎉 Hello, Code Detective! 🕵️</h1>
<p>Thanks for checking out Rails Blocks!</p>
<p>You're clearly someone who pays attention to details.</p>
<p>That's exactly the kind of developer we love!</p>
<div class="cta-section">
<button class="awesome-btn wiggle">You're awesome!</button>
<p><small>Seriously, keep being curious! 🚀</small></p>
</div>
<footer>
<p>Built with ❤️ by the Rails Blocks team</p>
<p>Now go build something amazing!</p>
</footer>
</div>
<script>
console.log("🎊 Bonus points for opening the console!");
console.log("Keep exploring and happy coding! 💻");
</script>
</body>
</html>
Playlist in a form
Track numbers renumber live while you drag, and each row carries a hidden position input ready for accepts_nested_attributes_for.
This code is available to Pro users only.
<!-- Hey curious person! -->
<!-- You seem to be sneaking around the code... -->
<!-- I hope you're enjoying the components! -->
<!-- Have a great day! -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Secret Message from Rails Blocks</title>
<style>
.secret-message {
font-family: 'Comic Sans MS', cursive;
text-align: center;
padding: 2rem;
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.wiggle { animation: wiggle 0.5s ease-in-out infinite; }
@keyframes wiggle {
0%, 100% { transform: rotate(0deg); }
25% { transform: rotate(1deg); }
75% { transform: rotate(-1deg); }
}
</style>
</head>
<body>
<div class="secret-message">
<h1>🎉 Hello, Code Detective! 🕵️</h1>
<p>Thanks for checking out Rails Blocks!</p>
<p>You're clearly someone who pays attention to details.</p>
<p>That's exactly the kind of developer we love!</p>
<div class="cta-section">
<button class="awesome-btn wiggle">You're awesome!</button>
<p><small>Seriously, keep being curious! 🚀</small></p>
</div>
<footer>
<p>Built with ❤️ by the Rails Blocks team</p>
<p>Now go build something amazing!</p>
</footer>
</div>
<script>
console.log("🎊 Bonus points for opening the console!");
console.log("Keep exploring and happy coding! 💻");
</script>
</body>
</html>
Locked and disabled items
The first and last steps are locked: they never move and nothing can pass them. The paused step can’t be picked up, but still makes room for the others.
This code is available to Pro users only.
<!-- Hey curious person! -->
<!-- You seem to be sneaking around the code... -->
<!-- I hope you're enjoying the components! -->
<!-- Have a great day! -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Secret Message from Rails Blocks</title>
<style>
.secret-message {
font-family: 'Comic Sans MS', cursive;
text-align: center;
padding: 2rem;
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.wiggle { animation: wiggle 0.5s ease-in-out infinite; }
@keyframes wiggle {
0%, 100% { transform: rotate(0deg); }
25% { transform: rotate(1deg); }
75% { transform: rotate(-1deg); }
}
</style>
</head>
<body>
<div class="secret-message">
<h1>🎉 Hello, Code Detective! 🕵️</h1>
<p>Thanks for checking out Rails Blocks!</p>
<p>You're clearly someone who pays attention to details.</p>
<p>That's exactly the kind of developer we love!</p>
<div class="cta-section">
<button class="awesome-btn wiggle">You're awesome!</button>
<p><small>Seriously, keep being curious! 🚀</small></p>
</div>
<footer>
<p>Built with ❤️ by the Rails Blocks team</p>
<p>Now go build something amazing!</p>
</footer>
</div>
<script>
console.log("🎊 Bonus points for opening the console!");
console.log("Keep exploring and happy coding! 💻");
</script>
</body>
</html>
Move buttons
Every drag should have a one-click alternative (WCAG 2.2, 2.5.7), and on a long list it is often the faster way anyway. Buttons with drag-and-drop#movePrevious or #moveNext move the row they sit in, exactly like a drop, and turn aria-disabled when the row can’t go further. The footer is locked, so nothing moves below it.
Homepage sections
Drag the handle, or use the arrows.
This code is available to Pro users only.
<!-- Hey curious person! -->
<!-- You seem to be sneaking around the code... -->
<!-- I hope you're enjoying the components! -->
<!-- Have a great day! -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Secret Message from Rails Blocks</title>
<style>
.secret-message {
font-family: 'Comic Sans MS', cursive;
text-align: center;
padding: 2rem;
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.wiggle { animation: wiggle 0.5s ease-in-out infinite; }
@keyframes wiggle {
0%, 100% { transform: rotate(0deg); }
25% { transform: rotate(1deg); }
75% { transform: rotate(-1deg); }
}
</style>
</head>
<body>
<div class="secret-message">
<h1>🎉 Hello, Code Detective! 🕵️</h1>
<p>Thanks for checking out Rails Blocks!</p>
<p>You're clearly someone who pays attention to details.</p>
<p>That's exactly the kind of developer we love!</p>
<div class="cta-section">
<button class="awesome-btn wiggle">You're awesome!</button>
<p><small>Seriously, keep being curious! 🚀</small></p>
</div>
<footer>
<p>Built with ❤️ by the Rails Blocks team</p>
<p>Now go build something amazing!</p>
</footer>
</div>
<script>
console.log("🎊 Bonus points for opening the console!");
console.log("Keep exploring and happy coding! 💻");
</script>
</body>
</html>
Sortable table rows
Mark the <tbody> as the list and each <tr> as an item. The lifted row keeps the table’s classes and column widths, so its cells stay lined up.
| Reorder | # | Feature | Votes | Status |
|---|---|---|---|---|
| 1 | Dark mode | 312 | Planned | |
| 2 | CSV export | 248 | In progress | |
| 3 | Two-factor login | 197 | Planned | |
| 4 | Slack notifications | 151 | Researching | |
| 5 | Custom domains | 96 | Researching |
This code is available to Pro users only.
<!-- Hey curious person! -->
<!-- You seem to be sneaking around the code... -->
<!-- I hope you're enjoying the components! -->
<!-- Have a great day! -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Secret Message from Rails Blocks</title>
<style>
.secret-message {
font-family: 'Comic Sans MS', cursive;
text-align: center;
padding: 2rem;
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.wiggle { animation: wiggle 0.5s ease-in-out infinite; }
@keyframes wiggle {
0%, 100% { transform: rotate(0deg); }
25% { transform: rotate(1deg); }
75% { transform: rotate(-1deg); }
}
</style>
</head>
<body>
<div class="secret-message">
<h1>🎉 Hello, Code Detective! 🕵️</h1>
<p>Thanks for checking out Rails Blocks!</p>
<p>You're clearly someone who pays attention to details.</p>
<p>That's exactly the kind of developer we love!</p>
<div class="cta-section">
<button class="awesome-btn wiggle">You're awesome!</button>
<p><small>Seriously, keep being curious! 🚀</small></p>
</div>
<footer>
<p>Built with ❤️ by the Rails Blocks team</p>
<p>Now go build something amazing!</p>
</footer>
</div>
<script>
console.log("🎊 Bonus points for opening the console!");
console.log("Keep exploring and happy coding! 💻");
</script>
</body>
</html>
Dropzones
Drag a file onto Archive or Trash. The zone lights up, the file shrinks into it, and the list closes the gap. With the keyboard, lift a file with Space and keep pressing ↑ past the first file to reach the zones. The buttons on each row (shown on hover, focus and touch screens) do the same in one click with drag-and-drop#sendTo, and the Undo bar (the undo target) brings the last file back.
- All tidy. Nothing left to sort.
- All tidy. Nothing left to sort.
This code is available to Pro users only.
<!-- Hey curious person! -->
<!-- You seem to be sneaking around the code... -->
<!-- I hope you're enjoying the components! -->
<!-- Have a great day! -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Secret Message from Rails Blocks</title>
<style>
.secret-message {
font-family: 'Comic Sans MS', cursive;
text-align: center;
padding: 2rem;
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.wiggle { animation: wiggle 0.5s ease-in-out infinite; }
@keyframes wiggle {
0%, 100% { transform: rotate(0deg); }
25% { transform: rotate(1deg); }
75% { transform: rotate(-1deg); }
}
</style>
</head>
<body>
<div class="secret-message">
<h1>🎉 Hello, Code Detective! 🕵️</h1>
<p>Thanks for checking out Rails Blocks!</p>
<p>You're clearly someone who pays attention to details.</p>
<p>That's exactly the kind of developer we love!</p>
<div class="cta-section">
<button class="awesome-btn wiggle">You're awesome!</button>
<p><small>Seriously, keep being curious! 🚀</small></p>
</div>
<footer>
<p>Built with ❤️ by the Rails Blocks team</p>
<p>Now go build something amazing!</p>
</footer>
</div>
<script>
console.log("🎊 Bonus points for opening the console!");
console.log("Keep exploring and happy coding! 💻");
</script>
</body>
</html>
Rails integration
Pick whichever fits the screen. All three happen on every drop that changes something.
- Hidden inputs. Any
data-drag-and-drop-target="position"input inside an item is rewritten with its new position, so a regular form submit saves the order. - Event.
drag-and-drop:movebubbles from the root after the drop withitem,id,fromandto(list ids),oldIndex,index(0-based),position(index + start-at),ids(the destination list in its new order) andfromIds(the source list after the move) in its detail. It is cancelable:preventDefault()puts the item back. - Request. Set
data-drag-and-drop-url-valueand{ from, to, index, position, ids, fromIds }is sent as JSON with the CSRF token.:idin the URL is replaced with the item id. Requests go out one at a time in the order of the moves, and a queued request is skipped when a newer move of the same item replaced it, so a slow response never overwrites a newer order. Turbo Stream responses are rendered. A failed or redirected request slides the item back (unless a newer move was made since) and firesdrag-and-drop:error. While a request is in flight the item hasdata-drag-and-drop-savingandaria-busy.
# app/views/tasks/index.html.erb: one list per status, all in one controller
# <div data-controller="drag-and-drop" data-drag-and-drop-url-value="/tasks/:id/move">
# <ul data-drag-and-drop-target="list" data-drag-and-drop-list-id="todo" aria-label="To do">
# <li data-drag-and-drop-target="item" data-drag-and-drop-item-id="<%= task.id %>">
# <span data-drag-and-drop-title><%= task.title %></span>
# config/routes.rb
resources :tasks do
patch :move, on: :member
end
# app/controllers/tasks_controller.rb
# Receives { "from": "todo", "to": "doing", "index": 1, "position": 2,
# "ids": ["17", "42", "8"], "fromIds": ["3", "9"] }
def move
task = Current.user.tasks.find(params[:id])
status = params.require(:to)
return head :unprocessable_entity unless Task.statuses.key?(status)
# `ids` is the list's full new order. Scope it to the user, so a request
# can't reorder anyone else's tasks.
ids = Array(params[:ids]).map(&:to_i)
Task.transaction do
task.update!(status: status)
tasks = Current.user.tasks.where(id: ids, status: status).index_by(&:id)
ids.each_with_index { |id, index| tasks[id]&.update_column(:position, index + 1) }
end
head :no_content
end
# Using acts_as_list? Replace the transaction with:
# task.update!(status: status)
# task.insert_at(params[:position].to_i) # position is 1-based
Reference
Targets
listis a sortable container: its direct children markeditemare sortable. Give every list adata-drag-and-drop-list-idand every item adata-drag-and-drop-item-id.handle(inside an item) restricts where a drag can start. Addtouch-noneto it for instant touch drags. Without a handle the whole item drags, except for links, buttons, form fields, and anything markeddata-drag-and-drop-no-drag.position(inputs) andindex(text) inside an item receive its position.countwith a matchingdata-drag-and-drop-list-idshows a list’s size, andemptyinside a list is shown only while it has no items. They stay in sync, including when items arrive through Turbo Streams.dropzonereceivesdrag-and-drop:drop. Name it withdata-drag-and-drop-zone-id. Adddata-drag-and-drop-effect="remove"to remove the dropped item, anddata-drag-and-drop-zone-url(with:id) plusdata-drag-and-drop-zone-method(defaultDELETE) to tell your server; if that request fails the item comes back.destroyon the hidden_destroyfield of a nested form: a removed item stays in the form, hidden, with the field set to1.undois shown forundo-timeoutms after a removal, andundoTextinside it receives the message. Put adrag-and-drop#undobutton in it.
List and item attributes
data-drag-and-drop-titleon the element that names an item: the focused item is then named by its title (the controller addsaria-labelledby), and announcements use it. Anaria-labelon the item wins. Lists use theiraria-label.data-drag-and-drop-accepts="todo bug"on a list only takes items coming from one of those lists, or whosedata-drag-and-drop-type(space-separated) has one of those tokens. An item can always go back to its own list.data-drag-and-drop-limit="5"on a list is a soft limit (see State attributes below); adddata-drag-and-drop-limit-strictto refuse items once it is full. For anything else, canceldrag-and-drop:accept. A list that refuses the item getsdata-drag-and-drop-refusingwhile the item is over it, and keyboard moves skip it.data-drag-and-drop-lockedpins an item in place: it never moves and nothing can pass it.data-drag-and-drop-disabledmakes an item undraggable while it still makes room for others.
Values
url: an endpoint with an:idplaceholder, replaced with the URL-encoded item id. Sent as JSON with the CSRF token;methoddefaults toPATCH. The body is{ from, to, index, position, ids, fromIds }. Reply with a Turbo Stream and it is rendered. A non-2xx response, or a redirect, animates the item back to where it came from.delay: press-and-hold time before a touch starts dragging (default200ms). Handles withtouch-noneskip it.distance: how far (px) a mouse or pen must travel before a press becomes a drag, so clicks still work (default4).start-at: the number of the first position, sopositionin events and requests isindex + start-at(default1, like acts_as_list).disabled: turns sorting off, for read-only lists. Items stay focusable and the arrow keys still move between them; the root getsdata-drag-and-drop-disabled. It can change at any time: a drag in flight is cancelled.messages: overrides for everything said to screen readers (see Translations below).axislocks the lifted item toxory.lift-scale(default1.03) andtilt(degrees, default0) shape the lifted item.undo-timeout(default6000ms) is how long theundotarget stays visible, longer while hovered or focused.
Actions
Put these on buttons, menu items or a <select> inside an item. They act on that item, or on the item whose data-drag-and-drop-item-id matches a data-drag-and-drop-id-param. Moves fire the same events, update the same inputs and send the same request as a drop.
drag-and-drop#movePrevious,drag-and-drop#moveNext,drag-and-drop#moveFirstanddrag-and-drop#moveLastmove the item one place, or to the start or end of its list (as far as locked items allow). A button that can’t move its item any further getsaria-disabled="true", so style it witharia-disabled:. Same actions as the Kanban component.change->drag-and-drop#moveToon a<select>moves the item to the chosen option:"done"(end of that list),"done:0"(its top), or":0"/":-1"(top / bottom of the item’s own list); the select is reset after the move. On a button, useclick->drag-and-drop#moveTowithdata-drag-and-drop-list-paramanddata-drag-and-drop-index-param(0-based, negative counts from the end).drag-and-drop#sendTowithdata-drag-and-drop-zone-paramsends the item to the dropzone with thatdata-drag-and-drop-zone-id, with the samedropandremoveevents.drag-and-drop#undoputs the last removed item back.drag-and-drop#refreshre-reads counts, limits and labels after you change the list some other way.
Methods
moveItem(itemOrId, list, index) moves an item from JavaScript, the way a drop does: animated, announced, drag-and-drop:move dispatched and saved. index counts from the end when negative (default -1). Pass { silent: true } for moves made elsewhere, like another user’s move arriving through a Turbo Stream: it only animates, with no drop rules, event, request or announcement. It returns whether the item moved. sendToZone(item, zone) does the same for a dropzone.
const root = document.querySelector("[data-controller~='drag-and-drop']")
const sortable = window.Stimulus.getControllerForElementAndIdentifier(root, "drag-and-drop")
sortable.moveItem("42", "done", 0) // top of Done, saved
sortable.moveItem("42", "done", -1, { silent: true }) // just animate it there
Keyboard
- The whole controller is one Tab stop: the arrow keys move focus between items when nothing is lifted.
- Space lifts the focused item, and drops it. Enter does the same, except on an item that is (or whose handle is) a link or a button: there Enter opens it, like a click.
- While an item is lifted, the arrow keys move it, spilling into the next list at either end (skipping lists that refuse it) and on to a dropzone after the last list. Home / End send it to the top or bottom of its list, Space or Enter drops it, and Tab drops it where it is.
- Esc cancels and returns the item, for pointer drags too. Every step is announced to screen readers.
State attributes
Every visual state is a data attribute, so you style it with Tailwind data-[…]: and group-data-[…]: variants on your own markup.
data-drag-and-drop-pressedon the grip while the pointer is down but the drag hasn’t started (on touch, only after 100 ms).data-drag-and-drop-draggingon an item marks the slot it leaves in the list:data-[drag-and-drop-dragging]:*:opacity-0empties it (prefer opacity overinvisible: controls withtransition-allwould flicker).data-drag-and-drop-liftedis on the item while it is lifted with the keyboard.data-drag-and-drop-overlayon the floating copy that follows the pointer (and the keyboard): shadow, ring, background. The copy lives on<body>so scroll containers never clip it; style items with their own classes rather than parent selectors.data-drag-and-drop-over,data-drag-and-drop-at-limit,data-drag-and-drop-over-limitanddata-drag-and-drop-refusingon lists, anddata-drag-and-drop-overon dropzones.data-drag-and-drop-over-limit-at-restonly updates once a drop has landed: use it for anything that changes the layout, so the list doesn’t resize under the pointer mid-drag.data-drag-and-drop-savingon an item (plusaria-busy="true") while its save request is in flight, and on the root while any request is.data-drag-and-drop-active="item"on the root while anything is dragged or lifted, anddata-drag-and-drop-disabledwhile sorting is off.- While an item is in the air, the controller can grow but never gets shorter (its
min-heightis held, like the Kanban board), so nothing below it moves under the pointer. It settles once the drop has landed. List heights are deliberately not animated: they are drop targets, and a target that resizes mid-drag is one you chase.
Events
drag-and-drop:start,drag-and-drop:endanddrag-and-drop:cancelwith{ item, id, kind }(startalso hasfrom;kindis always"item", like the Kanban’s"card") when a drag or keyboard lift begins, ends, or is cancelled.drag-and-drop:movewith{ item, id, from, to, oldIndex, index, position, ids, fromIds }, cancelable, after a drop or a one-click move.fromandtoare list ids,indexis zero-based,positionisindex + start-at,idsis the destination list’s order andfromIdsthe source list’s.preventDefault()puts the item back.drag-and-drop:acceptwith{ item, id, from, to, list }the first time a dragged item reaches another list, and before a one-click move into one, cancelable:event.preventDefault()makes the list refuse it.drag-and-drop:savedwith the move’s detail plus theresponseonce the request succeeds, anddrag-and-drop:errorwith the same detail pluserrorandresponsewhen it fails. A redirect counts as a failure (an expired session sent to the sign-in page saved nothing). Requests go out one at a time, in order; a queued request is skipped when a newer move of the same item replaced it.drag-and-drop:drop(cancelable) fires on a dropzone, followed bydrag-and-drop:removewhen the item was removed; itsdetail.undo()puts the item back, for your own toast.drag-and-drop:restorefollows an undo (detail.reasonis"undo") or a failed zone request ("error").
Translations
Everything said to screen readers can be replaced through data-drag-and-drop-messages-value, a JSON object with any of these keys: instructions, instructionsZones, pickedUp, lifted, moving, dropped, moved, cancelled, notAllowed, rejected, saveFailed, blocked, overZone, movedToZone, restored, zoneError, position, positionInList, unnamed and itemRole. Placeholders use Rails’ i18n syntax, so a locale file can be passed as it is: %{label}, %{position}, %{list}, %{zone}, %{index} and %{count}. The Kanban component uses the same keys. The defaults are at the top of the controller.
<%# config/locales/de.yml has a drag_and_drop: section with the same keys %>
<div data-controller="drag-and-drop"
data-drag-and-drop-messages-value="<%= t("drag_and_drop").transform_keys { |key| key.to_s.camelize(:lower) }.to_json %>">