jQuery UI Sortable: order of events

Learn jquery ui sortable: order of events with practical examples, diagrams, and best practices. Covers javascript, jquery, jquery-ui development techniques with visual explanations.

Understanding jQuery UI Sortable: The Order of Events

Illustration of a hand dragging an item in a list, representing jQuery UI Sortable functionality.

Explore the sequence of events fired by jQuery UI Sortable during drag-and-drop operations, and learn how to effectively use them for dynamic list management.

jQuery UI Sortable is a powerful widget that allows users to reorder elements in a list or grid using drag-and-drop. While its basic implementation is straightforward, understanding the precise order in which its events fire is crucial for building robust and responsive applications. This article delves into the event lifecycle of jQuery UI Sortable, providing a clear sequence of events and practical examples to help you manage your sortable lists effectively.

The Core Sortable Events

jQuery UI Sortable provides several events that allow you to hook into different stages of the drag-and-drop process. The most commonly used events are start, sort, change, over, out, update, and stop. Each event serves a specific purpose, providing opportunities to execute custom logic, update data models, or modify the UI.

sequenceDiagram
    participant User
    participant Sortable

    User->>Sortable: Mouse Down (on sortable item)
    activate Sortable
    Sortable->>Sortable: Item starts dragging
    Sortable->>User: `start` event fired
    Note right of Sortable: Drag helper created

    loop While dragging
        User->>Sortable: Mouse Move
        Sortable->>User: `sort` event fired (repeatedly)
        alt Position changed
            Sortable->>User: `change` event fired
        end
        alt Dragging over new list
            Sortable->>User: `over` event fired
        end
        alt Dragging out of list
            Sortable->>User: `out` event fired
        end
    end

    User->>Sortable: Mouse Up (drop item)
    Sortable->>Sortable: Item dropped
    alt Position changed or item moved to new list
        Sortable->>User: `update` event fired
    end
    Sortable->>User: `stop` event fired
    deactivate Sortable

Sequence of jQuery UI Sortable Events

Detailed Event Breakdown and Usage

Let's break down each event and understand when it's triggered and how you can leverage it in your applications.

$(function() {
    $("#sortable").sortable({
        start: function(event, ui) {
            console.log("1. start: Dragging started.", ui.item.text());
            // Perform actions when dragging begins, e.g., store initial position
        },
        sort: function(event, ui) {
            // console.log("2. sort: Item is being dragged.", ui.item.text());
            // This event fires continuously during dragging. Use sparingly for performance.
        },
        change: function(event, ui) {
            console.log("3. change: Position of item has changed within the list.", ui.item.text());
            // Update visual cues or temporary data structures
        },
        over: function(event, ui) {
            console.log("4. over: Helper is over a sortable list.", ui.item.text());
            // Useful for connected sortables, when helper enters a new list
        },
        out: function(event, ui) {
            console.log("5. out: Helper has left a sortable list.", ui.item.text());
            // Useful for connected sortables, when helper leaves a list
        },
        update: function(event, ui) {
            console.log("6. update: The DOM position of the item has changed.", ui.item.text());
            // This is the most common event for saving the new order to the backend.
            // It fires AFTER the DOM has been updated.
            var newOrder = $(this).sortable('toArray');
            console.log("New order:", newOrder);
        },
        stop: function(event, ui) {
            console.log("7. stop: Dragging stopped, item dropped.", ui.item.text());
            // Final cleanup or UI updates after the drag operation is complete.
        }
    });

    $("#sortable").disableSelection();
});

Example of all jQuery UI Sortable events in action.

Event Order in Detail:

  1. start: Fired once when the user begins dragging an item. This is the first event in the sequence.
  2. sort: Fired continuously as the item is dragged. This event can be very chatty, so use it carefully to avoid performance issues.
  3. change: Fired when the position of the dragged item changes relative to other sortable items in the list. This happens when the placeholder moves.
  4. over: Fired when the dragged item's helper enters a sortable list (especially relevant for connected sortables).
  5. out: Fired when the dragged item's helper leaves a sortable list (again, relevant for connected sortables).
  6. update: Fired when the DOM position of the sortable item has actually changed. This is typically the event you'll use to persist the new order to a database or update your application's state. It fires after the DOM has been modified by jQuery UI.
  7. stop: Fired once when the user releases the mouse button, ending the drag operation. This is the last event in the sequence, regardless of whether the item's position changed or not.

Handling Connected Sortables

When working with multiple connected sortable lists, the event order becomes slightly more complex, especially concerning the update event. If an item is moved from one list to another, the update event will fire on both the sender list (the list from which the item was dragged) and the receiver list (the list where the item was dropped). The sender property in the ui object is crucial here to distinguish between these two update events.

$(function() {
    $(".connected-sortable").sortable({
        connectWith: ".connected-sortable",
        update: function(event, ui) {
            var $this = $(this);
            if (ui.sender) {
                console.log("Update on SENDER list: Item '" + ui.item.text() + "' moved OUT of '" + $this.attr('id') + "'");
                // Logic for when an item leaves this list
            } else {
                console.log("Update on RECEIVER list: Item '" + ui.item.text() + "' moved INTO '" + $this.attr('id') + "'");
                // Logic for when an item enters or is reordered within this list
            }
            var newOrder = $this.sortable('toArray');
            console.log("New order for '" + $this.attr('id') + "':", newOrder);
        },
        stop: function(event, ui) {
            console.log("Stop event fired on '" + $(this).attr('id') + "'");
            // Final actions after drag-and-drop, regardless of list change
        }
    }).disableSelection();
});

Handling update events with connected sortable lists.

By understanding the precise order and purpose of each event, you can effectively manage the state of your sortable lists, update your backend, and provide a seamless user experience with jQuery UI Sortable.