Search code examples
javascriptjqueryangulardrag-and-drop

Drag & drop multiple items at once, as a stack


I'm trying to implement a system that allows me to drag multiple selected items at once, but once dragging starts, they should collapse into a stack with an integer showing how much items are being dragged, not individual items that keep their relative position.

I've been looking at existing Drag & Drop implementations and got multi drag working but I can't seem to find a library that allows my to override the drag proxy with my own implementation.

Anyone has an idea how to accomplish this? Or should I look into writing my own Drag & Drop solution using HTML5 Drag & Drop API or another library?

enter image description here


Solution

  • You could use helper to achieve this.

    $(document).ready(function() {
      $('#list-items [data-action="draggable"]').draggable({
        revert: true,
        helper: function() {
          var selected = $('#list-items [data-action="draggable"].selected');
          if (selected.length === 0) {
            $(this).addClass('selected');
            selected = $(this);
          }
          var container = $('<div/>').attr('id', 'draggingContainer');
          container.append('<div>' + selected.length + '</div>')
          container.append(selected.clone());
          return container;
        }
      });
      $('#list-items [data-action="draggable"]').click(function() {
        $(this).toggleClass('selected')
      });
    });
    .selected {
      background-color: rgba(13, 173, 253, 0.37)
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <ul id='list-items'>
      <li data-action='draggable'>elem 1</li>
      <li data-action='draggable'>elem 2</li>
      <li data-action='draggable'>elem 3</li>
      <li data-action='draggable'>elem 4</li>
      <li data-action='draggable'>elem 5</li>
      <li data-action='draggable'>elem 6</li>
    </ul>