Welcome to the jQuery Selectable tutorial! Today, we're going to dive into a powerful feature that enables you to interact with multiple elements as a group. This tutorial is designed for both beginners and intermediate learners. Let's get started!
š” Pro Tip: jQuery is a JavaScript library that simplifies HTML document traversing, event handling, and animation.
The Selectable feature allows users to select multiple items within a group by dragging a rectangular region around them. This is particularly useful for creating interactive user interfaces such as checklists, image galleries, or even text editors.
Before we dive in, make sure you have included the jQuery library in your HTML file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>Now, let's make some elements selectable. You'll need to apply the ui-widget and ui-selectable classes to the container holding the elements you want to make selectable.
<div id="selectable" class="ui-widget ui-selectable">
<p class="ui-selectee">Item 1</p>
<p class="ui-selectee">Item 2</p>
<p class="ui-selectee">Item 3</p>
</div>š Note: The ui-selectee class is applied to the individual elements you want to make selectable.
By default, the Selectable feature is enabled on the container. However, you can use the .selectable() method to configure selectable behavior.
$( "#selectable" ).selectable();Now, click and drag over the elements to select them!
The .selectable() method accepts several options, which you can pass as an object:
$( "#selectable" ).selectable({
// Options go here
});Here are some commonly used options:
selected: Defines the initially selected elements.stop: Determines the action to take when the user releases the mouse button (cancel, ignore, or default).filter: Filters which elements are selectable based on a jQuery selector.Which option should be used to define initially selected elements?
Let's create a simple todo list where users can select multiple items to delete.
<ul id="todo-list">
<li class="ui-state-default">Task 1</li>
<li class="ui-state-default">Task 2</li>
<li class="ui-state-default">Task 3</li>
</ul>$( function() {
$( "#todo-list" ).selectable({
stop: function( event, ui ) {
if ( ui.selected.length ) {
alert( "You selected: " + ui.selected.toArray().join( ', ' ) );
}
}
});
} );Now, when users select items, an alert will display the selected tasks.
That's it for the jQuery Selectable tutorial! You've learned how to make elements selectable and even create interactive user interfaces with minimal effort. Happy coding! š