Jquery Ui Library
Jquery Ui Library
Jquery Ui Library
#jquery-ui
Table of Contents
About 1
Remarks 2
Versions 2
Examples 3
Chapter 2: Accordion 6
Syntax 6
Parameters 6
Remarks 6
Examples 6
Chapter 3: Autocomplete 9
Examples 9
Simple example 9
Chapter 4: Button 10
Syntax 10
Parameters 10
Examples 10
Basic usage 10
Chapter 5: Datepicker 11
Examples 11
Initialization 11
Setting Minimum and Maximum dates for a datepicker 11
Chapter 6: Dialog 14
Syntax 14
Parameters 14
Remarks 16
Examples 17
Simple Example 17
Chapter 7: Draggable 24
Examples 24
Simple Example 24
Chapter 8: Icons 25
Syntax 25
Remarks 25
Examples 25
Basic usage 25
Parameters 26
Examples 26
Examples 28
Examples 30
Simple Example 30
Range Slider 30
Syntax 33
Parameters 33
Remarks 36
Examples 36
Simple Example 36
Syntax 40
Parameters 40
Remarks 40
Examples 40
Basic Example 40
Credits 41
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: jquery-ui-library
It is an unofficial and free jQuery UI Library ebook created for educational purposes. All the
content is extracted from Stack Overflow Documentation, which is written by many hardworking
individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official jQuery UI
Library.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to [email protected]
https://riptutorial.com/ 1
Chapter 1: Getting started with jQuery UI
Library
Remarks
jQuery UI is a JavaScript UI library, built on top of jQuery, offering a set of user interface
interactions, effects and widgets.
Versions
1.7.0 2009-03-06
1.7.1 2009-03-19
1.7.2 2009-06-12
1.7.4 2010-05-04
1.8.0 2010-03-23
1.8.1 2010-05-04
1.8.2 2010-06-07
1.8.4 2010-08-10
1.8.5 2010-09-17
1.8.6 2010-10-02
1.8.7 2010-12-10
1.8.8 2011-01-14
1.8.9 2011-01-21
1.8.10 2011-02-24
1.8.11 2011-03-18
1.8.12 2011-04-23
1.8.13 2011-05-17
1.8.14 2011-06-28
https://riptutorial.com/ 2
Version Release Date
1.8.15 2011-08-08
1.8.16 2011-08-18
1.8.17 2012-01-10
1.8.18 2012-02-23
1.8.19 2012-04-17
1.8.20 2012-04-30
1.8.21 2012-06-05
1.8.22 2012-07-24
1.8.23 2012-08-15
1.8.24 2012-09-28
1.9.0 2012-10-08
1.9.1 2012-10-25
1.9.2 2012-11-23
1.10.0 2013-01-17
1.10.1 2013-02-15
1.10.2 2013-03-14
1.10.3 2013-05-03
1.10.4 2014-01-17
1.11.0 2014-06-26
1.11.1 2014-08-13
1.11.2 2014-10-16
1.11.3 2015-02-12
1.11.4 2015-03-11
Examples
https://riptutorial.com/ 3
Adding the jQuery UI script & basic usage
To get started with the jQuery UI library, you'll need to add the jQuery script, the jQuery UI script,
and the jQuery UI stylesheet to your HTML.
First, download jQuery UI; choose the features you need on the download page. Unzip your
download, and put jquery-ui.css and jquery-ui.js (and jquery.js) in a folder where you can use
them from your HTML (e.g. with your other scripts and stylesheets.)
That's it! You can now use jQuery UI. For example, use the datepicker with the following HTML:
$("#date").datepicker();
The jQuery UI framework helps to extend and increase the User Interface controls for jQuery
JavaScript library.
When you wish to use jQuery UI, you will need to add these libraries to your HTML. A quick way to
start is using the Content Delivery Network available code sources:
jQuery Libraries
https://riptutorial.com/ 4
https://code.jquery.com/jquery-3.1.0.js
https://code.jquery.com/ui/1.12.0/jquery-ui.js
You can choose many different themes for jQuery UI and even Roll your Own Theme. For this
example, we will use 'Smoothness'. You add the theme via CSS.
jQuery UI CSS
https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css
When you have downloaded or selected your CDN, you will now want to add these libraries and
style sheets to your HTML so that your web page can now make use of the jQuery and jQuery UI.
The order in which you load the libraries is important. Call the jQuery library first, and then your
jQuery UI library. Since jQuery UI extends jQuery, it must be called after. Your HTML may look
something like the following.
<html>
<head>
<title>My First UI</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-
ui.css">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script>
$( function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
} );
</script>
</head>
<body>
<ul id="sortable">
<li class="ui-state-default">Item 1</li>
<li class="ui-state-default">Item 2</li>
<li class="ui-state-default">Item 3</li>
<li class="ui-state-default">Item 4</li>
<li class="ui-state-default">Item 5</li>
<li class="ui-state-default">Item 6</li>
<li class="ui-state-default">Item 7</li>
</ul>
</body>
</html>
https://riptutorial.com/ 5
Chapter 2: Accordion
Syntax
• $(function() { $( "#selecter" ).accordion(); });
• $(function() { $( "#selecter" ).accordion({ active: 2 }); });
• $(function() { $( "#selecter" ).accordion({ animate: 200 }); });
• $(function() { $( "#selecter" ).accordion({ collapsible: true }); });
Parameters
Parameter Detail
Remarks
More information can be found here: http://api.jqueryui.com/accordion/
Examples
Accordion Basic Usage
To use an accordion, one must have headers and content inside the headers in their HTML. Then
one must instantiate the accordion() method of jQuery UI.
<script>
$(function() {
$( "#accordion" ).accordion();
});
</script>
In the HTML:
https://riptutorial.com/ 6
<div id="accordion">
<h3>First header</h3>
<div>First content panel</div>
<h3>Second header</h3>
<div>Second content panel</div>
</div>
This will remove the accordion functionality completely and show default HTML removing all the
jQuery-UI elements.
This method will disable the accordion, i.e. the headers are not selectable making the content read
only and static.
This method will enable an accordion. This will enable a disabled accordion or simply do nothing
on an already enabled accordion.
This will return a PlainObject giving all the options representing the selected accordion. This will
https://riptutorial.com/ 7
contain all the values of the keys that are explained in the Parameters section.
This method takes parameters which are the basic optionNames explained in the parameter. One
can set the options like this:
This method recomputes the height of the accordion panels if headers or content was added or
removed in the DOM.
https://riptutorial.com/ 8
Chapter 3: Autocomplete
Examples
Simple example
The Autocomplete widgets provides suggestions while you type into the field.
<script>
$(document).ready(function() {
var tags = ["ask","always", "all", "alright", "one", "foo", "blackberry",
"tweet","force9", "westerners", "sport"];
$( "#tags" ).autocomplete({
source: tags
});
});
</script>
<input type='text' title='Tags' id='tags' />
https://riptutorial.com/ 9
Chapter 4: Button
Syntax
• $( ".selector" ).button();
• $( ".selector" ).button({ disabled: true });
• $( ".selector" ).button({ icons: { primary: "ui-icon-gear", secondary: "ui-icon-triangle-1-s" } });
• $( ".selector" ).button({ label: "custom label" });
• $( ".selector" ).button({ text: false });
Parameters
Examples
Basic usage
Create an input (or button, or anchor) html element and call button() method of jQuery UI.
<script>
$(function() {
$( "#myButton" ).button();
});
</script>
HTML
https://riptutorial.com/ 10
Chapter 5: Datepicker
Examples
Initialization
The datepicker is used to show an interactive date selector which is tied to a standard form input
field. It makes selecting of date for input tasks very easy and also it is also highly configurable.
Any input field can be bound with jquery-ui datepicker by the input field's selector (id,class etc.)
using datepicker() method like this -
<script>
$( ".inclas").datepicker({
minDate: new Date(2007, 1 - 1, 1)
maxDate: new Date(2008, 1 - 1, 1)
});
</script>
The following code will show week of the year number on the left side of the datepicker. By default
the week start on Monday, but it can be customized using firstDay option. The first week of the
year contains the first Thursday of the year, following the ISO 8601 definition.
The following example shows how you can set the date format in initialization with the dateFormat
https://riptutorial.com/ 11
option.
The following example shows how you can set the date format after initialization with the
dateFormat option.
Or predefined standard:
A default date format can be applied to all datepickers using the following example:
<script>
https://riptutorial.com/ 12
$.datepicker.setDefaults({
dateFormat: "yy-mm-dd"
});
</script>
jQuery datepicker has two options to allow displaying dropdowns for month and year selection.
These options make navigation through large timeframes easier.
https://riptutorial.com/ 13
Chapter 6: Dialog
Syntax
• $( ".selector" ).dialog( "option", "disabled" ); // Option Getter, specific
• $( ".selector" ).dialog( "option" ); // Option Getter all
• $( ".selector" ).dialog( "option", "disabled", true ); // Option Setter, specific
• $( ".selector" ).dialog( "option", { disabled: true } ); // Option Setter, multiple
• $( ".selector" ).dialog( "close" ); // Triggers close
• $( ".selector" ).dialog({ close: function() {} }); // Close overloading
• $( ".selector" ).on( "dialogclose", function( event, ui ) {} ); // Close overloading
Parameters
Parameter Description
Options
(Boolean) [Default: true] If set to true, the dialog will automatically open
autoOpen upon initialization. If false, the dialog will stay hidden until the open()
method is called.
(Boolean) [Default: true] Specifies whether the dialog should close when it
closeOnEscape
has focus and the user presses the escape (ESC) key.
(String) [Default: "close"] Specifies the text for the close button. Note that
closeText
the close text is visibly hidden when using a standard theme.
(String) The specified class name(s) will be added to the dialog, for
dialogClass
additional theming.
(Boolean) [Default: true] If set to true, the dialog will be draggable by the
draggable
title bar. Requires the jQuery UI Draggable widget to be included.
maxHeight (Number) [Default: false] The maximum height to which the dialog can be
https://riptutorial.com/ 14
Parameter Description
resized, in pixels.
(Number) [Default: false] The maximum width to which the dialog can be
maxWidth
resized, in pixels.
(Number) [Default: 150] The minimum height to which the dialog can be
minHeight
resized, in pixels.
(Number) [Default: 150] The minimum width to which the dialog can be
minWidth
resized, in pixels.
(Boolean) [Default: false] If set to true, the dialog will have modal
behavior; other items on the page will be disabled, i.e., cannot be
modal
interacted with. Modal dialogs create an overlay below the dialog but
above other page elements.
(String) Specifies the title of the dialog. If the value is null, the title attribute
title
on the dialog source element will be used.
Methods
Removes the dialog functionality completely. This will return the element
destroy
back to its pre-init state.
Retrieves the dialog's instance object. If the element does not have an
instance
associated instance, undefined is returned.
option Gets the value currently associated with the specified optionName.
option Gets an object containing key/value pairs representing the current dialog
https://riptutorial.com/ 15
Parameter Description
options hash.
Extension
Points
(event) Modal dialogs do not allow users to interact with elements behind
the dialog. This can be problematic for elements that are not children of
the dialog, but are absolutely positioned to appear as though they are.
_allowInteraction The _allowInteraction() method determines whether the user should be
allowed to interact with a given target element; therefore, it can be used to
whitelist elements that are not children of the dialog but you want users to
be able to use.
Events
drag (event, ui { position, offset }) Triggered while the dialog is being dragged.
(event, ui { position, offset }) Triggered when the user starts dragging the
dragStart
dialog.
dragStop (event, ui { position, offset }) Triggered after the dialog has been dragged.
Remarks
https://riptutorial.com/ 16
Parameter Source: http://api.jqueryui.com/dialog/
Examples
Simple Example
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window
can be moved, resized and closed with the 'x' icon.</p>
</div>
Usually we want to separate the creation of the dialog from its appearance. Then three steps are
needed.
2. Make it a dialog, note the autoOpen: false option that ensures that it will be closed at first
$( "#dialog" ).dialog({
autoOpen: false
});
Generally, dialog relies on a div within the HTML. Sometimes you may want to create a dialog
from scratch, programmatically. Here is an example of a complex modal dialog created
dynamically with interactive functions.
HTML
https://riptutorial.com/ 17
<h1>Existing Users:</h1>
<table id="users" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header ">
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>[email protected]</td>
<td>johndoe1</td>
</tr>
</tbody>
</table>
</div>
<button id="create-user">Create new user</button>
CSS
label,
input {
display: block;
}
input.text {
margin-bottom: 12px;
width: 95%;
padding: .4em;
}
fieldset {
padding: 0;
border: 0;
margin-top: 25px;
}
h1 {
font-size: 1.2em;
margin: .6em 0;
}
div#users-contain {
width: 350px;
margin: 20px 0;
}
div#users-contain table {
margin: 1em 0;
border-collapse: collapse;
width: 100%;
}
https://riptutorial.com/ 18
}
.ui-dialog .ui-state-error {
padding: .3em;
}
.validateTips {
border: 1px solid transparent;
padding: 0.3em;
}
jQuery
$(function() {
// Define variables for the dialog, form and a regular expression used to verify email
addresses in the form
var dialog, form,
emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-
9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
//Function called when form is submitted that will check all the form fields. If all fields
have text and all the text meets the requirements, the data is collected and added back to the
https://riptutorial.com/ 19
table.
function addUser() {
var valid = true;
allFields.removeClass("ui-state-error");
if (valid) {
$("#users tbody").append("<tr>" +
"<td>" + name.val() + "</td>" +
"<td>" + email.val() + "</td>" +
"<td>" + password.val() + "</td>" +
"</tr>");
dialog.dialog("close");
}
return valid;
}
https://riptutorial.com/ 20
widget-content ui-corner-all'>";
markup += "<label for='email'>Email</label><input type='text' name='email' id='email'
value='[email protected]' class='text ui-widget-content ui-corner-all'>\r\n";
markup += "<label for='password'>Password</label><input type='password' name='password'
id='password' value='xxxxxxx' class='text ui-widget-content ui-corner-all'>\r\n";
markup += "<input type='submit' tabindex='-1' style='position:absolute; top:-1000px'>\r\n";
// Assigning variables to be used for easy reference, post creation and amendment of dynamic
objects
var name = $("#name"),
email = $("#email"),
password = $("#password"),
allFields = $([]).add(name).add(email).add(password),
tips = $(".validateTips");
// Override the click event of the button to launch our dynamic dialog
$("#create-user").button().on("click", function() {
dialog.dialog("open");
});
});
Occasionally, we may want to display dialogs with more than one pane of content. jQuery UI offers
tabs that can be used in tandem with a dialog to make this possible. While it may be more
common to have tabs within a dialog's content container, this example will demonstrate how to
make a list of tabs the titlebar of the dialog.
HTML
<button id="openButton">
Open Dialog
</button>
<div id="dialog" style="display:none">
<div class="ui-tabs">
<ul>
<li><a href="#tab_1">Tab 1</a></li>
<li><a href="#tab_2">Tab 2</a></li>
</ul>
<div id="tab_1">
<p>Tab 1 content...</p>
</div>
<div id="tab_2">
<p>Tab 2 content...</p>
</div>
</div>
</div>
jQuery
$(document).ready(function() {
https://riptutorial.com/ 21
// Options to pass to the jQuery UI Dialog
var options = {
position: {
my: "left top",
at: "left top",
of: window
},
autoOpen: false
};
/* Initialization */
// Initialize the dialog
var dialog = $("#dialog").dialog(options);
// Find the list of tabs to make the titlebar, add the ui-dialog-titlebar class, and append
the close button
var tabbedTitlebar = dialog.find(".ui-tabs ul:first").addClass("ui-dialog-
titlebar").append(closeButton);
/* Arranging */
// Remove the initialTitlebar
$(initialTitlebar).remove();
If you like to show the dialog without the close button (i.e. the x button in the upper-right corner of
the dialog), perhaps because you want to force the user to select one of options or buttons in the
dialog itself:
$("#selector").dialog({
closeOnEscape: false,
https://riptutorial.com/ 22
dialogClass: "dialog-no-close",
});
Note: If you want to hide the entire title bar, use this CSS instead:
Alternatively, you can hide the close button in the dialog's initialization code:
$("#selector").dialog({
closeOnEscape: false,
open: function(event, ui) {
$(".ui-dialog-titlebar-close", $(this).parent()).hide();
}
});
https://riptutorial.com/ 23
Chapter 7: Draggable
Examples
Simple Example
<script>
$(function() {
$( "#draggable" ).draggable();
});
</script>
<div id="draggable" class="ui-widget-content">
<p>Drag me around</p>
</div>
You can use any element as an handle to drag another element around:
<script>
$(function() {
$( "#draggable" ).draggable({
handle: ".handle"
});
});
</script>
<div id="draggable">
<span class="handle">Handle</span>
<div>Content</div>
</div>
Fiddle
https://riptutorial.com/ 24
Chapter 8: Icons
Syntax
• .ui-icon-{icon type}-{icon sub description}-{direction}
Remarks
The icons are also integrated into a number of jQuery UI's widgets, such as accordion, button,
menu.
Examples
Basic usage
For a thick arrow pointing north in a span, add classes ui-icon and ui-icon-arrowthick-1-n:
For a triangle pointing south in a span, add classes ui-icon and ui-icon-triangle-1-s:
https://riptutorial.com/ 25
Chapter 9: jQuery UI Rotatable Plug-in
Parameters
Parameter Details
step an angle in degrees that the rotation will snap to if the shift key is held.
Examples
Initial Usage Example
<html>
<head>
<title>My Rotatable</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-
ui.css">
<link rel="stylesheet"
href="//cdn.jsdelivr.net/jquery.ui.rotatable/1.0.1/jquery.ui.rotatable.css">
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script
src="//cdn.jsdelivr.net/jquery.ui.rotatable/1.0.1/jquery.ui.rotatable.min.js"></script>
<script>
$(function(){
$('#target').rotatable();
});
https://riptutorial.com/ 26
</script>
</head>
<body>
<div id="target">Rotate me!</div>
</body>
</html>
https://riptutorial.com/ 27
Chapter 10: jquery ui sortable
Examples
jQuery UI Sortable - Drop Placeholder
This example of the Sortable using a Placeholder is common usage. Sortable is applied to a group
of DOM elements, allowing the user to move items around in the list via Drag'n Drop style actions.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Sortable - Drop Placeholder</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<style>
#sortable {
list-style-type: none;
margin: 0;
padding: 0;
width: 60%;
}
#sortable li {
margin: 0 5px 5px 5px;
padding: 5px;
font-size: 1.2em;
height: 1.5em;
}
html>body #sortable li {
height: 1.5em; line-height: 1.2em;
}
.ui-state-highlight {
height: 1.5em;
line-height: 1.2em;
}
</style>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script>
$( function() {
$( "#sortable" ).sortable({
placeholder: "ui-state-highlight"
}).disableSelection();
});
</script>
</head>
<body>
<ul id="sortable">
<li class="ui-state-default">Item 1</li>
<li class="ui-state-default">Item 2</li>
<li class="ui-state-default">Item 3</li>
<li class="ui-state-default">Item 4</li>
<li class="ui-state-default">Item 5</li>
<li class="ui-state-default">Item 6</li>
https://riptutorial.com/ 28
<li class="ui-state-default">Item 7</li>
</ul>
</body>
</html>
https://riptutorial.com/ 29
Chapter 11: Slider
Examples
Simple Example
A slider control uses draggable handles to select numeric values. Below is an example of a basic
slider initialization:
<script>
$(function() {
$( "#slider" ).slider();
});
</script>
<div id="slider"></div>
Range Slider
Range sliders provide 2 draggable handles to select numeric values. The slider's initialization must
provide a range option set to true to create a range slider:
<script>
$(function() {
$( "#range-slider" ).slider({
range: true
});
});
</script>
<div id="range-slider"></div>
A slider element can have its value set on initialization by providing a value option. This option is a
number:
$( "#slider" ).slider({
value: 5
});
A range slider can also have its values set in this way by providing a values option. This option is
an array of numbers:
$( "#range-slider" ).slider({
range: true,
values: [5, 25]
});
In addition to providing initial values, the minimum value, maximum value, and handle interval can
https://riptutorial.com/ 30
be defined with the min, max, and step options, respectively:
$( "#range-slider" ).slider({
range: true,
min: 0, // The lowest possible value will be 0
max: 100, // The highest possible value will be 100
step: 5, // The slider handles will lock in at intervals of 5
values: [0, 100]
});
The slider provides an event called slide that will trigger whenever the mouse moves during a
slider handle drag. This function holds a reference to the slide event and a reference to the slider
ui object. The ui object holds a jQuery object for the handle being moved and the value(s) of the
slider.
Single-Handle Slider:
var value;
$( "#slider" ).slider({
slide: function(event, ui) {
value = ui.value;
}
});
Range Slider:
var lowValue;
var highValue;
$( "#range-slider" ).slider({
range: true,
slide: function(event, ui) {
lowValue = ui.values[0];
highValue = ui.values[1];
}
});
Note: The slide event is intended to respond to active mouse motion and will not trigger if the
slider values are changed programmatically. To react to these events, use the change event.
The slider provides an event called change that will trigger after the mouse completes a slider
handle drag or if the value(s) have been changed programmatically. This function holds a
reference to the slide event and a reference to the slider ui object. The ui object holds a jQuery
object for the handle being moved and the value(s) of the slider.
One example could be having to display new information after a slider's values have been updated
by another element's event. Let's use a select element for demonstration where the value of the
https://riptutorial.com/ 31
slider is programmatically set in when the value of the select changes:
HTML
<select id="setting">
<option value="1">Low</option>
<option value="2">Medium</option>
<option value="3">High</option>
</select>
<div id="slider"></div>
<div id="display-value"></div>
JavaScript
$(function() {
$( "#slider" ).slider({
min: 0,
max: 11,
// This will trigger when the value is programmatically changed
change: function(event, ui) {
$( "#display-value" ).text(ui.value);
}
});
$( "#setting" ).change(function () {
switch ($(this).val()) {
case "1":
$( "#slider" ).slider( "value", 3 ); // Sets the value of a slider programmatically
break;
case "2":
$( "#slider" ).slider( "value", 7 ); // Sets the value of a slider programmatically
break;
case "3":
$( "#slider" ).slider( "value", 11 ); // Sets the value of a slider programmatically
break;
}
});
});
Note: It's in these circumstances that the slide event would not trigger and the change event is
needed. However, if elements need to react to the slider values changing as the handle is being
dragged, the slide event will be necessary.
https://riptutorial.com/ 32
Chapter 12: Sortable
Syntax
• $("#sortable").sortable({ /*Options Here*/ }); //Initialise Sortable
Parameters
Parameter Description
Options
(String) [Default: false] The directions that the item can be dragged (x
axis
or y)
(Element, Selector, String) [Default: false] The element that items are
containment
constrained to
(Object) [Default: false] Defines the position that the helper looks like
cursorAt
its being moved from
(Boolean) [Default: true] If false items from this sortable can not be
dropOnEmpty
placed in empty sortables
https://riptutorial.com/ 33
Parameter Description
grid (Array) [Default: false] Defines a grid to snap the helper to ([ x,y ])
items (Selector) [Default: "> *"] Defines the items that should be sortable
opacity (Number 0.01 to 1) [Default: false] Defines the opacity for the helper
(Boolean, Number) [Default: false] The time that it takes the helper to
revert
slide into its new position
scroll (Boolean) [Default: true] Whether to scroll when at edges of the page
(Number) [Default: 20] Defines how close to the edge of the page the
scrollSensitivity
cursor needs to be to start scrolling
Methods
Cancels the current sort and returns the elements back to their
cancel()
position before the sort started
option() Gets key value pairs of all the options for the sortable
https://riptutorial.com/ 34
Parameter Description
option(String, Any) Sets the value of the option specified by the String
Sets one or more options with the object being key value pairs of
option(Object)
options
Serializes the items ids (by default) into a string that can be submitted
or appended to a url Object options: {key: sets the key in the
serialize(Object) serialized string, attribute:[Default "id"] sets the attribute to look at,
expression:[Default: "/(.+)-=_/"] regex to split the attribute in to key
value pairs}
Serializes the sortable items id into an array. The object can contain a
toArray(Object) parameter attribute which has the attribute to put into the array default
is id
Events
Triggers before sorting stops when the helper has being shiftered to
beforeStop(event, ui)
the same position as the placeholder
deactivate(event, ui) Triggered when sorting stops. This goes to all connected lists as well
out(event, ui) Triggered when the item is moved out of the sortable list
over(event, ui) Triggered when the item is moved into a sortable list
Triggered when an item from a connected list has being dropped into
receive(event, ui)
another one. Target is the receiving list
Triggered when an item from a connected list has being dropped into
remove(event, ui)
another one. Target is the giving list
https://riptutorial.com/ 35
Parameter Description
Triggered when sorting stops and the DOM position has being
update(event, ui)
updated
Remarks
Official Documentation here
Examples
Simple Example
Take any list and add an identifier to the outer wrapper (ul, div)
<ul id="sortable">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
In your jquery:
$(function(){
$('#sortable').sortable({
//pass all options in here
});
});
This will allow all the li in the #sortable wrapper to be dragged and dropped in the list
This used the flex layout with the sortable to create a grid of responsive boxes that can be moved
around by dragging and dropping.
HTML
<div id="sortable">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
https://riptutorial.com/ 36
<div>5</div>
</div>
JS
$(function(){
$('#sortable').sortable({
//pass all options in here
});
});
CSS
#sortable{
width: 500px;
display: flex;
flex-wrap: wrap;
}
#sortable div {
margin: 10px;
background-color: #f00;
flex-basis: 100px;
height: 100px;
}
This example uses a class on the placeholder to turn it into a line and make it take up no room.
HTML
<div id="sortable">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
JS
$("#sortable").sortable({
placeholder: 'placeholder',
helper: 'clone',
start: function(event, ui){
ui.item.show();
}
});
CSS
#sortable div{
background-color: #f00;
width: 50px;
https://riptutorial.com/ 37
height: 50px;
margin: 10px;
padding: 0px;
}
#sortable div.placeholder{
height: 4px;
margin: -7px 10px;
}
Cancelling and Reverting a sortable is not strongly documented. The helps show how moving an
item from one list to another connected list can be conditionally cancelled. by default, this is not
animated by sortable, this example includes an animation.
Result: List #2 only accepts items that have a class of acceptable. Both lists can be sorted naturally
otherwise.
HTML
<div class="ui-widget">
<ul id="sortable1" class="connectedSortable">
<li class="ui-state-default acceptable">Item 1</li>
<li class="ui-state-default">Item 2</li>
<li class="ui-state-default">Item 3</li>
<li class="ui-state-default">Item 4</li>
<li class="ui-state-default">Item 5</li>
</ul>
<ul id="sortable2" class="connectedSortable">
<li class="ui-state-default">Item 6</li>
<li class="ui-state-default acceptable">Item 7</li>
</ul>
</div>
CSS
.ui-widget {
position: relative;
}
.connectedSortable {
border: 1px solid #eee;
width: 142px;
min-height: 20px;
list-style-type: none;
margin: 0;
padding: 5px 0 0 0;
float: left;
margin-right: 10px;
}
#sortable1 {
background: #fff;
}
https://riptutorial.com/ 38
#sortable2 {
background: #999;
}
.connectedSortable li {
margin: 0 5px 5px 5px;
padding: 5px;
font-size: 1.2em;
width: 120px;
}
JavaScript
$(function() {
$(".connectedSortable").sortable({
connectWith: ".connectedSortable",
receive: function(e, ui) {
var $self = $(this);
var $item = ui.item;
var $sender = ui.sender;
// Restrict condition to only one specific list if desired
if ($(e.target).attr("id") == "sortable2") {
if ($item.hasClass("acceptable")) {
// Item Accepted
console.log($self.attr("id") + " accepted item from: #" + $sender.attr("id") + " > "
+ $item.text());
} else {
// Item Rejected
console.log($self.attr("id") + " rejected item from: #" + $sender.attr("id") + " > "
+ $item.text());
// Animate the return of the items position
$item.css("position", "absolute").animate(ui.originalPosition, "slow", function() {
// Return the items position control to it's parent
$item.css("position", "inherit");
// Cancel the sortable action to return it to it's origin
$sender.sortable("cancel");
});
}
}
}
}).disableSelection();
});
https://riptutorial.com/ 39
Chapter 13: Spinner
Syntax
• $( "#id" ).spinner();
• $( "#id" ).spinner({min:0,max:100,step:5,spin:function( event, ui ) {}});
Parameters
Parameters Detail
step How much the value increases by on spinner click, can be decimal
spin Can be used to check the spinner value, ui.value and do something
Remarks
Official Example
Official Documentation
Examples
Basic Example
Makes entering numbers a bit handier by showing a set of arrows on the right side of the input.
HTML
https://riptutorial.com/ 40
Credits
S.
Chapters Contributors
No
3 Autocomplete JF
4 Button Theodore K.
7 Draggable empiric, J F
8 Icons Theodore K.
jQuery UI Rotatable
9 Twisty
Plug-in
https://riptutorial.com/ 41