HomeServiceContact
Drupal
min read
July 19, 2024

Drag-and-drop made easy in Drupal with core's sortable.js

Drag-and-drop made easy in Drupal with core's sortable.js
Table of contents

Creating a seamless and interactive user experience is more important than ever. One powerful tool for achieving this goal is drag-and-drop functionality, which Improves user engagement by allowing intuitive manipulation of elements directly on a webpage.

Drupal 10, renowned for its flexibility and robustness as a content management system (CMS), Uses Sortable.js—a JavaScript library designed to simplify the creation of drag-and-drop interfaces.

This blog explores Sortable.js in-depth, covering its functionality, benefits, and practical steps for implementing and customizing it effectively within Drupal projects.

What is sortable.js?

Sortable.js is a JavaScript library that facilitates drag-and-drop sorting for various web elements. It supports touch devices and provides various customization options, making it a flexible choice for developers.

Key features

Drag-and-drop functionality for sorting items.

  • Touch support for mobile and tablet devices.
  • Customizable options for enhanced flexibility.
  • Event handling to trigger custom actions during drag-and-drop interactions.

Sortable.js is built into Drupal 10 core, enabling developers to implement drag-and-drop functionality effortlessly without requiring additional libraries or complex configuration. This integration streamlines the process and ensures seamless compatibility with other Drupal features. Notably, Sortable.js is utilized in Drupal's Layout Builder, enhancing the flexibility and user-friendliness of the layout design process within the core system.

Benefits

Enhanced user experience


Drag-and-drop interfaces offer a more interactive and engaging user experience. Users can effortlessly reorder items, manage lists, and complete tasks intuitively, improving your website's overall usability.

Flexibility and customization


Sortable.js provides a wide range of customization options, enabling developers to adapt the drag-and-drop functionality to their specific requirements. From defining draggable elements to customizing animations, Sortable.js equips developers with the tools to craft unique user experiences.

Ease of implementation


With Sortable.js integrated into Drupal, adding drag-and-drop functionality becomes a breeze. Developers can quickly incorporate this feature into their projects without extensive coding or configuration, saving both time and effort.

Implementing Drag-and-Drop with sortable.js in Drupal

  • Step-by-Step Guide:

       1. Using sortable.js as a dependency in .libraries.yml

library-name:
  version: 1.x
  js:
    js/js-name.js: {}
  dependencies:
    - core/sortable

  1. Attaching the library to specific pages or blocks
  2. Creating Draggable Elements

       Define the HTML structure of the elements you want to make draggable: 

<ul id="sortable-list">
  <li class="sortable-item">Item 1</li>
  <li class="sortable-item">Item 2</li>
  <li class="sortable-item">Item 3</li>
</ul>

        Initialize sortable.js on the container element:

var el = document.getElementById('sortable-list');
var sortable = new Sortable(el, {
  animation: 150,
});

Creating Draggable Elements

Restricting Drag-and-Drop in specific containers

In certain scenarios, you may want to restrict drag-and-drop functionality within specific containers to maintain order or prevent unintended actions.

Implementation guide:

  1. Container identification: Identify the containers where you want to restrict drag-and-drop functionality. Assign unique IDs or classes to these containers.
  2. Using sortable.js options: Utilize sortable.js options to enforce restrictions. For example, to prevent dragging items out of a specific container:

var container1 = document.getElementById('container1');
var container2 = document.getElementById('container2');

var sortable1 = new Sortable(container1, {
  group: 'shared',
  animation: 150,
});

var sortable2 = new Sortable(container2, {
  group: {
    name: 'shared',
    pull: false,
    put: true
  },
  animation: 150,
});



Restricting Drag-and-Drop in specific containers

In the above example, the user can drag an item from Container 1 to Container 2 but vice versa is restricted so the user is not able to add the item to Container 1 from Container 2

Advanced customizations and tips

Custom animations and effects:

Enhance the drag-and-drop experience by adding custom animations and effects using CSS and JavaScript. Sortable.js allows you to specify animation durations and easing functions for smooth transitions. For example:

/* Custom CSS for animation effects */
.draggable-item {
  transition: transform 0.2s ease-in-out;
}

.draggable-item.dragging {
  opacity: 0.7;
  transform: scale(1.1);
}
// JavaScript to apply custom animations
var container1 = document.getElementById('container1');
var container2 = document.getElementById('container2');

var sortable1 = new Sortable(container1, {
  group: 'shared',
  animation: 150,
  onStart: function (/**Event*/evt) {
    evt.item.classList.add('dragging');
  },
  onEnd: function (/**Event*/evt) {
    evt.item.classList.remove('dragging');
  }
});

var sortable2 = new Sortable(container2, {
  group: {
    name: 'shared',
    pull: false,
    put: true
  },
  animation: 150,
});



Drag and drop custom animations and effects

Handling events

Sortable.js provides various events such as onStart, onEnd, onAdd, and onRemove. Use these events to trigger custom actions during drag-and-drop interactions, such as updating the database or modifying other elements on the page. Here's an example:

var container = document.getElementById('container');

var sortable = new Sortable(container, {
  animation: 150,
  onAdd: function (evt) {
    console.log('Item added:', evt.item);
    // Custom action, e.g., update the database
    updateDatabase(evt.item);
  },
  onEnd: function (evt) {
    console.log('Drag ended:', evt.item);
    // Custom action, e.g., modify other elements on the page
    updateUI(evt.item);
  }
});

function updateDatabase(item) {
  // Example function to update the database
  console.log('Updating database with item:', item);
}

function updateUI(item) {
  // Example function to modify UI elements
  console.log('Updating UI for item:', item);
}



Handling events

  • Performance optimization: For complex projects with numerous draggable elements, optimize performance by debouncing event handlers, minimizing DOM manipulations, and leveraging Sortable.js's built-in options for efficient rendering.

Conclusion

Sortable.js, integrated into the Drupal core, offers a powerful and flexible solution for implementing drag-and-drop functionality in your projects. By enhancing user experience, providing customization options, and simplifying implementation, Sortable.js empowers developers to create intuitive and engaging interfaces. By leveraging the power of Sortable.js and Drupal, you can create dynamic, user-friendly web applications that stand out in today's competitive digital landscape.

Written by
Editor
No art workers.
We'd love to talk about your business objectives