Upgrade to Pro to unlock this component

Access all premium components, AI-ready documentation, and lifetime access to updates.

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.

  • Review pull requests 3 open
  • Write the release notes v2.4
  • Reply to customer emails 12 unread
  • Plan next sprint Thursday
  • Update the roadmap Q1

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.

  • Inbox

    Everything assigned to you

  • Projects

    Boards, cycles and roadmaps

  • Documents

    Specs and meeting notes

  • Reports

    Velocity and burndown charts

  • Teams

    People and permissions

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.

  • Brand refresh

    24 shots

  • Mobile onboarding

    18 shots

  • Pricing page

    9 shots

  • Illustrations

    41 shots

  • Dashboard v3

    32 shots

  • Icon set

    120 shots

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
  • Created at
  • Plan
  • Country
  • MRR

Visible columns

3/5
  • Customer
  • Email
  • Status

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

  • Ship the billing fix 9:30
  • Design review with Mia 11:00
  • Send the investor update 16:00

Tomorrow 2

  • Interview: senior designer 10:00
  • Draft the Q1 plan 14:00

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.

Up next

5 tracks · 27 min

  1. 1 Midnight City M83 4:03
  2. 2 Tadow Masego & FKJ 5:01
  3. 3 Nights Frank Ocean 5:07
  4. 4 Weird Fishes Radiohead 5:18
  5. 5 Open Eye Signal Jon Hopkins 7:48

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.

  1. 1 Request submitted Employee Fixed
  2. 2 Manager approval Direct manager
  3. 3 Budget check Department lead
  4. 4 Legal review Paused until January Paused
  5. 5 Security review IT team
  6. 6 Payment released Finance Fixed

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.

  1. Hero Headline, subheading and call to action
  2. Customer logos Six grayscale logos
  3. Features Three columns with icons
  4. Pricing Monthly and yearly plans
  5. FAQ Eight questions
  6. Footer Always last

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.

Archive
Trash
  • XLS Q4-forecast.xlsx 184 KB
  • PDF Brand-guidelines.pdf 2.4 MB
  • PNG Homepage-hero.png 960 KB
  • DOC Interview-notes.docx 48 KB
  • AI Old-logo-final-v7.ai 5.1 MB

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:move bubbles from the root after the drop with item, id, from and to (list ids), oldIndex, index (0-based), position (index + start-at), ids (the destination list in its new order) and fromIds (the source list after the move) in its detail. It is cancelable: preventDefault() puts the item back.
  • Request. Set data-drag-and-drop-url-value and { from, to, index, position, ids, fromIds } is sent as JSON with the CSRF token. :id in 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 fires drag-and-drop:error. While a request is in flight the item has data-drag-and-drop-saving and aria-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

  • list is a sortable container: its direct children marked item are sortable. Give every list a data-drag-and-drop-list-id and every item a data-drag-and-drop-item-id.
  • handle (inside an item) restricts where a drag can start. Add touch-none to it for instant touch drags. Without a handle the whole item drags, except for links, buttons, form fields, and anything marked data-drag-and-drop-no-drag.
  • position (inputs) and index (text) inside an item receive its position. count with a matching data-drag-and-drop-list-id shows a list’s size, and empty inside a list is shown only while it has no items. They stay in sync, including when items arrive through Turbo Streams.
  • dropzone receives drag-and-drop:drop. Name it with data-drag-and-drop-zone-id. Add data-drag-and-drop-effect="remove" to remove the dropped item, and data-drag-and-drop-zone-url (with :id) plus data-drag-and-drop-zone-method (default DELETE) to tell your server; if that request fails the item comes back.
  • destroy on the hidden _destroy field of a nested form: a removed item stays in the form, hidden, with the field set to 1.
  • undo is shown for undo-timeout ms after a removal, and undoText inside it receives the message. Put a drag-and-drop#undo button in it.

List and item attributes

  • data-drag-and-drop-title on the element that names an item: the focused item is then named by its title (the controller adds aria-labelledby), and announcements use it. An aria-label on the item wins. Lists use their aria-label.
  • data-drag-and-drop-accepts="todo bug" on a list only takes items coming from one of those lists, or whose data-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); add data-drag-and-drop-limit-strict to refuse items once it is full. For anything else, cancel drag-and-drop:accept. A list that refuses the item gets data-drag-and-drop-refusing while the item is over it, and keyboard moves skip it.
  • data-drag-and-drop-locked pins an item in place: it never moves and nothing can pass it. data-drag-and-drop-disabled makes an item undraggable while it still makes room for others.

Values

  • url: an endpoint with an :id placeholder, replaced with the URL-encoded item id. Sent as JSON with the CSRF token; method defaults to PATCH. 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 (default 200 ms). Handles with touch-none skip it.
  • distance: how far (px) a mouse or pen must travel before a press becomes a drag, so clicks still work (default 4).
  • start-at: the number of the first position, so position in events and requests is index + start-at (default 1, 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 gets data-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).
  • axis locks the lifted item to x or y. lift-scale (default 1.03) and tilt (degrees, default 0) shape the lifted item. undo-timeout (default 6000 ms) is how long the undo target 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#moveFirst and drag-and-drop#moveLast move 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 gets aria-disabled="true", so style it with aria-disabled:. Same actions as the Kanban component.
  • change->drag-and-drop#moveTo on 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, use click->drag-and-drop#moveTo with data-drag-and-drop-list-param and data-drag-and-drop-index-param (0-based, negative counts from the end).
  • drag-and-drop#sendTo with data-drag-and-drop-zone-param sends the item to the dropzone with that data-drag-and-drop-zone-id, with the same drop and remove events.
  • drag-and-drop#undo puts the last removed item back. drag-and-drop#refresh re-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-pressed on the grip while the pointer is down but the drag hasn’t started (on touch, only after 100 ms). data-drag-and-drop-dragging on an item marks the slot it leaves in the list: data-[drag-and-drop-dragging]:*:opacity-0 empties it (prefer opacity over invisible: controls with transition-all would flicker). data-drag-and-drop-lifted is on the item while it is lifted with the keyboard.
  • data-drag-and-drop-overlay on 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-limit and data-drag-and-drop-refusing on lists, and data-drag-and-drop-over on dropzones. data-drag-and-drop-over-limit-at-rest only 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-saving on an item (plus aria-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, and data-drag-and-drop-disabled while sorting is off.
  • While an item is in the air, the controller can grow but never gets shorter (its min-height is 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:end and drag-and-drop:cancel with { item, id, kind } (start also has from; kind is always "item", like the Kanban’s "card") when a drag or keyboard lift begins, ends, or is cancelled.
  • drag-and-drop:move with { item, id, from, to, oldIndex, index, position, ids, fromIds }, cancelable, after a drop or a one-click move. from and to are list ids, index is zero-based, position is index + start-at, ids is the destination list’s order and fromIds the source list’s. preventDefault() puts the item back.
  • drag-and-drop:accept with { 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:saved with the move’s detail plus the response once the request succeeds, and drag-and-drop:error with the same detail plus error and response when 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 by drag-and-drop:remove when the item was removed; its detail.undo() puts the item back, for your own toast. drag-and-drop:restore follows an undo (detail.reason is "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 %>">

Table of contents

Powered by

Get notified when new components come out