Sort items Sortable interaction

Lecture



Interaction Sortable allows you to change the order of the elements in a set by dragging them from one place to another. To apply the Sortable interaction, select the element containing the individual objects that you want to sort, and call the sortable () method . The corresponding simple example is shown below:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>jQuery UI</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/jquery-ui.min.js"></script> <link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/themes/sunny/jquery-ui.css"> <style type="text/css"> div.sortable { width: 100px; background-color: lightgrey; font-size: large; float: left; margin: 6px; text-align: center; border: medium solid black; padding: 10px;} </style> <script type="text/javascript"> $(function() { $('#sortContainer').sortable(); }); </script> </head> <body> <div id="sortContainer"> <div id="item1" class="sortable ui-state-error">Элемент 1</div> <div id="item2" class="sortable ui-state-error">Элемент 2</div> <div id="item3" class="sortable ui-state-error">Элемент 3</div> </div> </body> </html></code> Запустить пример 

In this example, we create a series of div elements and assign the class sortable to them. To create an interaction, we select the parent div element (whose id attribute is equal to sortContainer) and call the sortable () method. As a result, we can change the order of the three div elements by dragging them to new positions. This process is illustrated in the figure:

  Sort items Sortable interaction

Here, to demonstrate the interaction of the Sortable, an element called "Element 2" is dragged to the right in the browser window. As soon as he passes an element called "Element 3", the elements are rearranged and arranged in a new order. In this case, the element was moved one position, but nothing prevents you from dragging elements to several positions at once.

Determining the order of sorted items

In some cases, it is necessary to determine in which order the elements are arranged after they are dragged by the user. To get this information, you can call the toArray method , which returns a JavaScript array containing the values ​​of the id attribute of the elements being sorted.

Below is an example of displaying the current order of elements on the console after clicking a button:

 ... $(function() { $('#sortContainer').sortable(); $('<div id=buttonDiv><button>Получить порядок</button></div>').appendTo('body'); $('button').button().click(function() { var order = $('#sortContainer').sortable("toArray"); for (var i = 0; i < order.length; i++) { console.log("Position: " + i + " ID: " + order[i]); } }) }); ... 

As a result of clicking on the button, the toArray method is called, and the contents of the resulting array are output to the console:

  Sort items Sortable interaction

Sortable interaction setup

Sortable interaction largely depends on the Draggable interaction described in the previous article. This means that all Draggable interaction options (such as axis or tolerance) with the same effect can be used to configure Sortable interaction. In this regard, I will not re-describe in detail all the settings and will focus only on those that are peculiar only to the Sortable interaction and are most often used. Their list is given in the table below, and detailed descriptions are contained in the following sections:

Sortable Interaction Properties
Property Description
connectWith Identifies another sorted container element with which a link should be established, providing the possibility of mutual movement of elements between containers. The default is false; it corresponds to the absence of such connections
dropOnEmpty If this option is false, then items cannot be moved to the associated sorted container when it is empty. The default is true.
items Defines a selector that sets which elements will be sortable. The default value is "> *", it corresponds to the selection of all descendants of the element for which the sortable () method was called
placeholder Specifies the class to be assigned to the element created to fill the position taken by the item being sorted before it is moved to the new location.

Linking sorted containers to each other

In the sorting tools provided by the jQuery UI plug-in, I like the ability to bind two containers with the Sortable interaction functionality, which allows you to move items from one container to another. This is achieved using the connectWith option used to specify a selector that selects an element with which such a link should be established.

By defining the connectWith property for both elements, you can make this connection two-way, as shown in the example below:

 <!DOCTYPE html> ... <style type="text/css"> div.sortable { width: 100px; background-color: lightgrey; font-size: large; margin: 4px; text-align: center; border: medium solid black; padding: 10px;} #fruitContainer {position: absolute; right:50px} #flowerContainer {position: absolute; left:50px} div.flower {background-color: lightgreen} </style> <script type="text/javascript"> $(function() { $('#fruitContainer').sortable({ connectWith: '#flowerContainer' }); $('#flowerContainer').sortable({ connectWith: '#fruitContainer' }); }); </script> </head> <body> <div id="fruitContainer" class="sortContainer"> <div id="fruit_1" class="sortable fruit">Яблоко</div> <div id="fruit_2" class="sortable fruit">Апельсин</div> <div id="fruit_3" class="sortable fruit">Банан</div> <div id="fruit_4" class="sortable fruit">Груша</div> </div> <div id="flowerContainer" class="sortContainer"> <div id="flower_1" class="sortable flower">Астра</div> <div id="flower_2" class="sortable flower">Пион</div> <div id="flower_3" class="sortable flower">Лилия</div> <div id="flower_4" class="sortable flower">Орхидея</div> </div> </body> </html> Запустить пример 

In this example, two groups of elements are created, and the sortable () method is called for the container element of each group. To connect groups to each other, use the connectWith option. The result is shown in the picture:

  Sort items Sortable interaction

Associating a roaming item with a container to be sorted

It is also possible to link the elements to be moved and sorted. To do this, use the connectToSortable option in the floating element, specifying as its value a selector that selects the sorting container element with which you want to establish a connection. The example below shows how this can be done:

 <!DOCTYPE html> ... <script type="text/javascript"> $(function() { $('#fruit_1').draggable({ connectToSortable: '#flowerContainer', helper: "clone" }); $('#flowerContainer').sortable(); }); </script> </head> <body> <div id="fruitContainer" class="sortContainer"> <div id="fruit_1" class="sortable fruit">Яблоко</div> </div> <div id="flowerContainer" class="sortContainer"> <div id="flower_1" class="sortable flower">Астра</div> <div id="flower_2" class="sortable flower">Пион</div> <div id="flower_3" class="sortable flower">Лилия</div> <div id="flower_4" class="sortable flower">Орхидея</div> </div> </body> </html> Запустить пример 

In this example, the number of items in the fruit list is reduced to one, which is made relocatable and associated with the color list. This ensures the possibility of adding a relocatable element to the container being sorted, as shown in the figure:

  Sort items Sortable interaction

This works flawlessly in cases where the value of the helper property of a floating element is clone. With other values ​​of this property, correct results are also obtained, but error messages are displayed.

Selection of items to be sorted

You can choose at your discretion which of the elements contained in the container can participate in sorting. To do this, use the items option, which takes as a value the selector of the elements that you want to make sortable. Items that do not match the selectors cannot be rearranged in the container being sorted. The corresponding example is shown below:

 ... $(function() { $('div.flower:odd').css("background-color", "salmon") $('#flowerContainer').sortable({ items: '.flower:even' }); }); ... Запустить пример 

In this example, with the help of the items option, it is determined that only even items that are contained in the container should be sortable.

When working with the items option, you should be aware of one particular feature. An element that does not correspond to the selector cannot be dragged to a new position, unless it has been previously ousted from its position by another element. So, for example, in the above example, if the element "Asters" is shifted to another position and at the same time forcibly displaces the element "Peonies", being once ousted from its initial position, the element "Peonies" acquires the ability to move and sort as if matched the selector specified by the items option.

Styling the empty position

By dragging an item to another location, it leaves behind an empty position. The placeholder option allows you to assign an empty position to a certain CSS class. This feature is convenient to use to visually highlight the place in the document that is ready to accept the element. An example of using the placeholder option is shown below:

 <!DOCTYPE html> ... <style type="text/css"> div.sortable { width: 100px; background-color: lightgrey; font-size: large; margin: 4px; text-align: center; border: medium solid black; padding: 10px;} #flowerContainer {position: absolute; left:50px} div.flower {background-color: lightgreen} .emptySpace {border: medium dotted red; height: 36px; margin: 4px} </style> <script type="text/javascript"> $(function() { $('#flowerContainer').sortable({ placeholder: 'emptySpace' }); }); </script> </head> <body> <div id="flowerContainer" class="sortContainer"> <div id="flower_1" class="sortable flower">Астра</div> <div id="flower_2" class="sortable flower">Пион</div> <div id="flower_3" class="sortable flower">Лилия</div> <div id="flower_4" class="sortable flower">Орхидея</div> </div> </body> </html> Запустить пример 

In this example, I defined an emptySpace class that sets the height and size of the fields, as well as the dotted red border for the elements to which it is applied. This class is set as the value of the placeholder option, and, as shown in the figure, when an element is dragged, the emptySpace class is assigned to the empty space:

  Sort items Sortable interaction

Sortable Interaction Methods

All standard jQuery UI methods are defined for Sortable interaction, plus a few additional ones that are specific for working with sortable elements. These methods are listed in the table below:

Sortable Interaction Methods
Method Description
sortable ("toArray") Returns an array containing an ordered list of id attribute values ​​(see previous example of using this method)
sortable ("refresh") Updates Sortable Interaction Cache Status
sortable ("cancel") Cancels the result of applying the last sort operation.

Undo the last sort result

The cancel method allows you to prevent items from being sorted. This opportunity should not be abused, because in fact it means ignoring the actions taken by the user. If you still use the cancel method, then make sure the user knows why this happens. An example of using the cancel method with the update event is shown below. The update event occurs when the user releases the mouse button by dragging the item.

 <!DOCTYPE html> ... <style type="text/css"> div.sortable { width: 100px; background-color: lightgrey; font-size: large; margin: 4px; text-align: center; border: medium solid black; padding: 10px;} </style> <script type="text/javascript"> $(function() { $('#error').dialog({autoOpen: false, modal: true, title: "Ошибка!"}) $('#flowerContainer').sortable({ update: function() { var sortedItems = $('#flowerContainer').sortable("toArray"); if (sortedItems[0] != "item_1") { $('#error').dialog("open") $('#flowerContainer').sortable("cancel") } } }); }); </script> </head> <body> <div id="error">Ha первом месте должен быть "Король"</div> <div id="flowerContainer" class="sortContainer"> <div id="item_1" class="sortable ">Король</div> <div id="item_2" class="sortable ">Дама</div> <div id="item_3" class="sortable ">Валет</div> <div id="item_4" class="sortable">10</div> </div> </body> </html> Запустить пример 

In this example, the cancel method is called if the King element is not in the first place in the new element order created by the user. To notify the user about the problems using the Dialog widget. Changes affecting the order of the other elements are allowed to take effect.

Sortable Interaction Events

Interaction Sortable supports all events defined for the Draggable interaction, which were described in a previous article. In addition, the Sortable interaction supports a number of its own events, a list of which is given in the table below:

Sortable Interaction Events
Event Description
change Occurs when an item changes position as a result of user-made sorting.
receive Occurs when an item is moved to a given sortable container element from another related sortable container element.
remove Occurs when an item is moved from this sortable container element to another related sortable container element.
sort Occurs with each mouse movement during the sorting process.
update Occurs when the user has completed moving the item, provided that the order of the items has been changed.

When each of these events occurs, the jQuery UI provides additional information through an event passed to the event handler as an argument to the ui object, whose properties are listed in the table below:

Sortable Interaction Ui Properties
Property Description
helper Returns an auxiliary element
position Returns information about the current location of the auxiliary element as an object with top and left properties
item Returns a jQuery object containing the item to be moved.
placeholder Returns a jQuery object representing the position from which the item being sorted was moved to or where
sender Returns a jQuery object containing the associated sorted container element in which the moved element was previously located (in the absence of associated sorted containers, the value of this property is null)

An example of using the ui object together with the sort and change events is shown below:

 Запустить пример <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>jQuery UI</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/jquery-ui.min.js"></script> <link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/themes/sunny/jquery-ui.css"> <style type="text/css"> div.sortable {width: 100px; background-color: lightgrey; font-size: large; margin: 4px; text-align: center; border: medium solid black; padding: 10px;} #flowerContainer {position: absolute; left:10px} #info {position: absolute; right: 10px; border: medium solid black; padding: 4px} div.flower {background-color: lightgreen} </style> <script type="text/javascript"> $(function() { $('#flowerContainer').sortable({ sort: function(event, ui) { $('#itemId').text(ui.item.attr("id")) }, change: function(event, ui) { $('#pos').text($('#flowerContainer *').index(ui.placeholder)) } }); }); </script> </head> <body> <div id="flowerContainer" class="sortContainer"> <div id="flower_1" class="sortable flower">Астра</div> <div id="flower_2" class="sortable flower">Пион</div> <div id="flower_3" class="sortable flower">Лилия</div> <div id="flower_4" class="sortable flower">Орхидея</div> </div> <div id="info" class="ui-widget"> <div>ID элемента: <span id="itemId">не определено</span></div> <div>Позиция: <span id="pos">не определено</span></div> </div> </body> </html> 

Here, events are used to display information about the sort operation being performed. Function — The sort event handler reads the value of the ui.item property and gets the value of the id attribute of the item being moved. The change event handler reads the value of the ui.placeholder property and uses the index method to calculate the position of the placeholder element among the sorted elements.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone