How to remove an item that is pulled away from it's list?

aamiri picture aamiri · Feb 22, 2012 · Viewed 10.2k times · Source

here is a simple question. I have a 'ul' which i have made sortable via jquery-ui's sortable() function. I want to remove elements when they are dragged off the list. The way i have it implemented works in the sense that when i drag an element away from the list it gets removed, but it also gets removed when i just rearrange the list. How do i achieve the behavior i am looking for without this unintended behavior. Below is all the code:

<html>
<head>
    <link type="text/css" href="jquery-ui/css/ui-lightness/jquery-ui-1.8.17.custom.css" rel="Stylesheet" /> 
    <script type="text/javascript" src="jquery-ui/js/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="jquery-ui/js/jquery-ui-1.8.17.custom.min.js"></script>

    <script type="text/javascript">
    $(function(){
        $('#sortme').sortable({
            out: function(event, ui){
                ui.item.remove();
            }
        });
        $('#sortme').disableSelection();
    });
    </script>

    <style>
    li{
        list-style-type: none;
        width: 200px;
        height: 50px;
        border: 1px solid #000;
        text-align: center;
        box-sizing: border-box;
        padding-top: 15px;
    }
    </style>
    <title> jqui sort test </title>

</head>
<body>
    <ul id='sortme'>
        <li>0</li>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
    </ul>
</body>
</html>

Thank you for your help!

Answer

Drew picture Drew · Feb 24, 2012

You could try to use a variable to check if the items you are dragging is dragged out of its parent container.

You can use the over and out events of the jQuery UI sortable to assign the value for this variable and then execute the removal of the dragged item on the beforeStop event.

here is a demo of what I have come up with: http://jsfiddle.net/drewP/m7VJq/1/

let me know if it works for you.