Tuesday, April 1, 2014

jQuery UI: Containing Sortables

The sortable widget has an option called containment. This means that when the user picks up a sortable item with the mouse, the movement is constrained by this option value. By default, there is no such restriction in place — the user is free to move the item around on the page. This can lead to problems in understanding what they're actually supposed to do with the item. For example, basic sortables mean taking an li element, and moving it around in the parent ul element. If the user can drag the element anywhere on the page, and there's nowhere to drop it, that's not an ideal experience.

The containment option is used for exactly this purpose, as this demonstration illustrates. For simple sortable lists, you should always use the containment option.

Something else you can do in conjunction with the containment option is setting the axis option. For vertical lists, you would set the axis option to "y". This provides the user with a smooth, and intuitive sorting interaction.

$("#sortable").sortable({
    axis: 'y',
    containment: 'parent'
});