mrcrazylee
mrcrazylee

Reputation: 273

jQuery UI: Sortable: Placeholder clone of item being sorted

I have a list that I want to make sortable. I've done this by using jQuery UI Sortable. What I want to do is use a custom placeholder for the position the list item can be dropped. What I can't figure out is how to make a placeholder that is a clone of the item being sorted. Instead of an empty placeholder, I would like to show a clone of the item being sorted so you get a kind of a 'preview' so to speak.

In short, ui.item[0].outerHTML is what I want to use as a custom placeholder, I just can't seem to get this.

  <script>
  $(function() {
    $( "#menu" ).sortable({
        start: function(event,ui) {
            console.log(ui.item[0].outerHTML);
        },
        placeholder: {
            element: function(event,ui) {
                console.log(ui.item[0].outerHTML);
            }
        }
    });
    $( "#menu" ).disableSelection();
  });
  </script>

The above is what I have now, but that doesn't work obviously. Is there an easy way to get this done with only sortable?

Upvotes: 6

Views: 15298

Answers (2)

Jim Geurts
Jim Geurts

Reputation: 20429

Based on https://stackoverflow.com/a/2156422/3085

<style>
  .sortable-placeholder {
    opacity: 0.3;
  }
</style>
<script>
  $(function() {
    var sortableList = $('#menu');
    sortableList.sortable({
      axis: 'y',
      revert: true,
      scroll: false,
      cursor: 'move',
      placeholder: 'sortable-placeholder',
      start: function(event, ui) {
        ui.placeholder.html(ui.item.html());
      }
    });
    sortableList.disableSelection();
  });
</script>

Upvotes: 9

mrcrazylee
mrcrazylee

Reputation: 273

After a bit of tinkering (i got inspired from this related question), I came to the following solution:

In the start event I clone the original item that is being sorted. I pass the clone on to the placeholder where I can update it's contents. (ui.item is not available here)

<script>
$(function() {
    $("#menu").sortable({
        start: function( event, ui ) {
            clone = $(ui.item[0].outerHTML).clone();
        },
        placeholder: {
            element: function(clone, ui) {
                return $('<li class="selected">'+clone[0].innerHTML+'</li>');
            },
            update: function() {
                return;
            }
        }

    });
});
</script>

Upvotes: 13

Related Questions