2

I am using jQuery UI Droppable plugin...

Somehow, my Draggable <li> element Class is getting removed after dropping. :(

How can I maintain the same CSS class for <li> tag after dropping the element

AFter dropping the <li class="one">Item 1</li> to Cart Area, I want to keep the same class to the <li> element as <li class="one">Item 1</li> where currently it is getting removed automatically.

Please check the Code Below...

HTML

<div id="products">
  <h2>Drag</h2>
  <div id="catalog">
      <ul>
        <li class="one">Item 1</li>
        <li class="two">Item 2</li>
        <li class="three">Item 3</li>
        <li class="four">Item 4</li>
        <li class="five">Item 5</li>
        <li class="six">Item 6</li>
      </ul>
  </div>
</div>

<div id="cart">
  <h2>Drop Here...</h2>
  <div class="ui-widget-content">
    <ol>
      <li class="placeholder">Add your items here</li>
    </ol>
  </div>
</div>

jQuery

$(function() {
    $( "#catalog li" ).draggable({
        appendTo: "body",
        helper: "clone"
    });
    $( "#cart ol" ).droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
        accept: ":not(.ui-sortable-helper)",
        drop: function( event, ui ) {
            $( this ).find( ".placeholder" ).remove();
            $( "<li></li>" ).html( ui.draggable.html() ).appendTo( this );
        }
    }).sortable({
        items: "li:not(.placeholder)",
        sort: function() {
            $( this ).removeClass( "ui-state-default" );
        }
    });
});

FIDDLE


Reddy
  • 1,477
  • 29
  • 79

3 Answers3

1

Change this line:

$( "<li></li>" ).html( ui.draggable.html() ).appendTo( this );    

to this:

$(ui.draggable).appendTo(this);

or

$(ui.draggable).clone().appendTo(this);

or

$( "<li class='"+$(ui.draggable).attr("class")+"'></li>" ).html( ui.draggable.html() ).appendTo( this );    

Your code is creating a new li.

Demo: http://jsfiddle.net/kux7x16y/5/

K K
  • 17,794
  • 4
  • 30
  • 39
1

add the class of your draggable li to the new li

 $( "<li class='"+ui.draggable.attr('class')+"' ></li>" ).html( ui.draggable.html() ).appendTo( this );

here is the Demo

http://jsfiddle.net/ReddyPrasad/kux7x16y/3/

Islam Zedan
  • 656
  • 4
  • 21
0

In your drop function, just append the ui.draggable object instead, no need for the overhead of creating your own element to represent the dragged object.

drop: function( event, ui ) {
    $( this ).find( ".placeholder" ).remove();
    $(ui.draggable).appendTo(this);
}

DEMO

Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148