Search code examples
javascriptjqueryjquery-uidraggabledroppable

drag, drop and delete elements selectively with jquery ui


Good day all. I have a simple interface, with 3 "zones". A list of elements that the user has, a place where the user can drag the elements he has and can sort them, and a place where the user can drag any element and if this element is from the second group, the element is deleted.

this is what I've done so far:

<div class="col-md-12">
        <h1 id="trash" style="background:#f00;">drop here to delete (trash)</h1>
        </div>
    <div class="col-md-12">
    <h1>take your elements from here (library)</h1>
        <div class="group">
            <ul class="playlists">
                <li class="mymedia" data-id="1453">element 0</li>
                <li class="mymedia" data-id="6565">element 1</li>
                <li class="mymedia" data-id="1222">element 2</li>
                <li class="mymedia" data-id="8888">element 3</li>
            </ul>
        </div>
    </div>
    <div class="col-md-12">
    <h1>drop here your elements, and sort them (playlist)</h1>
        <div class="group">

            <ul class="playlists droppable" style="background:#777; min-height:30px;">

            </ul>
        </div>
    </div>

and the javascript:

 $('.droppable').sortable();

    $(".mymedia").draggable({
        connectToSortable: '.droppable',
        helper: 'clone'
    });

    $('#trash').droppable({
        drop: function (event, ui) {
            ui.draggable.remove();
        }
    });

https://jsfiddle.net/peorthyr/dfvxt8g7/

what i'm missing is a little tricky. I want that only the elements dropped into the playlist are deletable (by now, dragging any element into the trash, will delete it), while the elements into the "library" aren't deletable, but only draggable into the playlist. I've tryed this, but with no luck:

$('.droppable').sortable({
drop: function (event, ui) {
            ui.draggable.addClass("deletable");
        }});

    $(".mymedia").draggable({
        connectToSortable: '.droppable',
        helper: 'clone'
    });

    $('#trash').droppable({
        drop: function (event, ui) {
            ui.draggable.hasClass("deletable").remove();
        }
    });

what i'm mistaking? may I ask you help on this?


Solution

  • You could handle it adding a class and remove only element getting this class, e.g:

    $('.droppable').sortable({
        stop: function (event, ui) {
            ui.item.addClass('dropped');
        }
    });
    
    $(".mymedia").draggable({
        connectToSortable: '.droppable',
        helper: 'clone'
    });
    
    $('#trash').droppable({
        drop: function (event, ui) {
            if (!ui.draggable.hasClass('dropped')) return false;
            ui.draggable.remove();
        }
    });
    

    -jsFiddle-