3

I'd like to (via a keyboard operator) select multiple items in an unordered list and drag them to another point in the same list with jQuery Sortable.

T J
  • 42,762
  • 13
  • 83
  • 138
tbeseda
  • 1,838
  • 3
  • 16
  • 25

1 Answers1

2
  1. Select items to sort
  2. Create a custom helper
  3. Hide the selected items until sort is done
  4. Resize the placeholder according to the selection
  5. Manually detach selected items from the current position and attach them to the new position after sort
  6. Show the hidden items (undo step 3) after step5

Here's how I did (Modifying my answer for this question):

$(function() {
  $('ul').on('click', 'li', function() {
    $(this).toggleClass('selected');
  });

  $("ul").sortable({
    revert: true,
    helper: function(e, item) {
      if (!item.hasClass('selected')) item.addClass('selected');
      var elements = $('.selected').not('.ui-sortable-placeholder').clone();
      var helper = $('<ul/>');
      item.siblings('.selected').addClass('hidden');
      return helper.append(elements);
    },
    start: function(e, ui) {
      var elements = ui.item.siblings('.selected.hidden').not('.ui-sortable-placeholder');
      ui.item.data('items', elements);
      var len = ui.helper.children().length;
      var height = ui.item.height() + 5;
      ui.helper.height((len * height))
      ui.placeholder.height((len * height))
    },
    receive: function(e, ui) {
      ui.item.before(ui.item.data('items'));
    },
    stop: function(e, ui) {
      ui.item.siblings('.selected').removeClass('hidden');
      $('.selected').removeClass('selected');
    }
  });

});
* {
  margin: 0;
  padding: 0;
}
#sortable {
  width: 300px;
  padding: 5px;
  margin-right: 100px;
  background: #eee;
  border: 1px solid black;
}
ul li {
  width: 250px;
  margin: 5px;
  padding: 5px;
  font-size: 1.2em;
  cursor: move;
  background-color: white;
  list-style-type: none;
}
.selected {
  background: red !important;
}
.hidden {
  display: none !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<ul id="sortable">
  <li>Item #1</li>
  <li>Item #2</li>
  <li>Item #3</li>
  <li>Item #4</li>
  <li>Item #5</li>
</ul>

(Select multiple items by clicking each of them in the demo)

Community
  • 1
  • 1
T J
  • 42,762
  • 13
  • 83
  • 138
  • This approach is ok, but when I was testing dragging items between multiple sortable areas I had problem with the use of `hidden` class, so I fixed using `hide()` method instead. Actually sortable uses hide instead of `hidden` class, so it is better to use the same. – p1nox Aug 26 '15 at 23:47