Recently I wanted to create a user interface where people could re-order lists of items and move items from one list to another. The interface had to be something special so I wanted people to be able to do this by dragging items in their web browser. To do this I started with an unordered list where each list item was another unordered list:
If you viewed it in the browser without styling you would see:
List 1
- Item 1
- Item 2
- Item 3
List 2
- Item 4
- Item 5
- Item 6
List 3
- Item 7
- Item 8
- Item 9
Next, I added some JavaScript that used the jQuery UI sortable. With just 18 lines of Javascript I had the whole thing working perfectly with alerts telling me where items were moving to, the list they were in, and if the lists were re-ordered.
$(function() { // This allows the lists to be re-ordered $(".lists").sortable({ forcePlaceholderSized: true, stop: function(event, ui) { var list = ui.item.children('ul').attr('id').replace('list_', ''); window.alert('Moving list ' + list + ' to position ' + ui.item.index()); }, }); // This allows the items to be re-ordered providing you add them to a list $(".list").sortable({ connectWith: ".list", forcePlaceholderSized: true, stop: function(event, ui) { var item = ui.item.attr('id').replace('item_', ''); var list = ui.item.parent().attr('id').replace('list_', ''); window.alert('Moving item ' + item + ' to list ' + list + ' position ' + ui.item.index()); }, }); });
At this point, I hooked it up to my applications API using jQuery AJAX functions and everyone worked great! Here’s what it looks like with a bit of CSS thrown in:
Moving an item from one list to another
Moving an item from one list to another
Re-ordering the lists
Post A Comment:
0 comments: