So you're working on a project that involves creating a sortable list using jQuery? Awesome! In this article, we're going to dive into a neat little trick that will allow users to delete an item from thesortable list just by dragging it out. Yes, it's as cool as it sounds. Let's get started.
First things first, you'll need to have jQuery and jQuery UI set up in your project. If you haven't already, include the necessary CDN links in your HTML file:
Next, make sure you have a list of items that you want to make sortable. You can set up a simple unordered list in your HTML:
<ul id="sortable-list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
Now, let's write the jQuery code that will make our list sortable and enable the drag-out deletion feature:
$(document).ready(function() {
$("#sortable-list").sortable({
axis: 'y',
containment: 'parent',
start: function(event, ui) {
ui.item.data('start_pos', ui.item.index());
},
update: function(event, ui) {
var start_pos = ui.item.data('start_pos');
var end_pos = ui.item.index();
if (end_pos !== start_pos) {
// Item has been moved
// You can perform additional actions here
}
}
});
$("#sortable-list").disableSelection();
$("#sortable-list li").draggable({
connectToSortable: "#sortable-list",
helper: "clone",
start: function(event, ui) {
$(this).hide();
},
stop: function(event, ui) {
$(this).show();
}
});
});
In this code snippet, we're initializing the sortable feature on our list with the `sortable()` method. We're also setting the axis to 'y' to enable vertical dragging and containing the list within its parent element. The `start` and `update` functions are used to track the initial and final positions of an item during dragging.
Additionally, we're making the list items draggable using the `draggable()` method. The `connectToSortable` option allows items to be dragged back into the list after they've been dragged out. We're also hiding the original item when it's being dragged and showing it again when the dragging stops.
With this setup, users can now drag items in the list to reorder them. If they drag an item outside the list completely, it will be deleted. How cool is that?
Feel free to customize and enhance this functionality to suit your specific needs. Have fun experimenting with jQuery and creating awesome interactive experiences!