You can create new widgets from scratch, using just the $.Widget
object as a base to inherit from, or you can explicitly inherit from existing jQuery UI or third-party widgets. Defining a widget with the same name as you inherit from even allows you to extend widgets in place.
jQuery UI contains many widgets that maintain state and therefore have a slightly different usage pattern than typical jQuery plugins. All of jQuery UI's widgets use the same patterns, which is defined by the widget factory. So if you learn how to use one widget, then you'll know how to use all of them.
Looking for tutorials about the widget factory? Check out the articles on the jQuery Learning Center.
Note: This documentation shows examples using the progressbar widget but the syntax is the same for every widget.
Initialization
In order to track the state of the widget, we must introduce a full life cycle for the widget. The life cycle starts when the widget is initialized. To initialize a widget, we simply call the plugin on one or more elements.
$( "#elem" ).progressbar();
This will initialize each element in the jQuery object, in this case the element with an id of "elem"
.
Options
Because progressbar()
was called with no parameters, the widget was initialized with its default options. We can pass a set of options during initialization to override the defaults:
$( "#elem" ).progressbar({ value: 20 });
We can pass as many or as few options as we want during initialization. Any options that we don't pass will just use their default values.
You can pass multiple options arguments. Those arguments will be merged into one object (similar to $.extend( true, target, object1, objectN )
). This is useful for sharing options between instances, while overriding some properties for each one:
var options = { modal: true, show: "slow" }; $( "#dialog1" ).dialog( options ); $( "#dialog2" ).dialog( options, { autoOpen: false });
All options passed on init are deep-copied to ensure the objects can be modified later without affecting the widget. Arrays are the only exception, they are referenced as-is. This exception is in place to support data-binding, where the data source has to be kept as a reference.
The default values are stored on the widget's prototype, therefore we have the ability to override the values that jQuery UI sets. For example, after setting the following, all future progressbar instances will default to a value of 80:
$.ui.progressbar.prototype.options.value = 80;
The options are part of the widget's state, so we can set options after initialization as well. We'll see this later with the option method.
Methods
Now that the widget is initialized, we can query its state or perform actions on the widget. All actions after initialization take the form of a method call. To call a method on a widget, we pass the name of the method to the jQuery plugin. For example, to call the value()
method on our progressbar widget, we would use:
$( "#elem" ).progressbar( "value" );
If the method accepts parameters, we can pass them after the method name. For example, to pass the parameter 40
to the value()
method, we can use:
$( "#elem" ).progressbar( "value", 40 );
Just like other methods in jQuery, most widget methods return the jQuery object for chaining.
$( "#elem" ) .progressbar( "value", 90 ) .addClass( "almost-done" );
Each widget will have its own set of methods based on the functionality that the widget provides. However, there are a few methods that exist on all widgets, which are documented below.
Events
All widgets have events associated with their various behaviors to notify you when the state is changing. For most widgets, when the events are triggered, the names are prefixed with the widget name and lowercased. For example, we can bind to progressbar's change
event which is triggered whenever the value changes.
$( "#elem" ).bind( "progressbarchange", function() { alert( "The value has changed!" ); });
Each event has a corresponding callback, which is exposed as an option. We can hook into progressbar's change
callback instead of binding to the progressbarchange
event, if we want to.
$( "#elem" ).progressbar({ change: function() { alert( "The value has changed!" ); } });
All widgets have a create
event which is triggered upon instantiation.
Instance
The widget's instance can be retrieved from a given element using the instance()
method.
$( "#elem" ).progressbar( "instance" );
If the instance()
method is called on an element that is not associated with the widget, undefined
is returned.
$( "#not-a-progressbar" ).progressbar( "instance" ); // undefined
The instance is stored using jQuery.data()
with the widget's full name as the key. Therefore, the :data
selector can also determine whether an element has a given widget bound to it.
$( "#elem" ).is( ":data('ui-progressbar')" ); // true $( "#elem" ).is( ":data('ui-draggable')" ); // false
Unlike instance()
, :data
can be used even if the widget being tested for has not loaded.
$( "#elem" ).nonExistentWidget( "instance" ); // TypeError $( "#elem" ).is( ":data('ui-nonExistentWidget')" ); // false
You can also use :data
to get a list of all elements that are instances of a given widget.
$( ":data('ui-progressbar')" );
Properties
All widgets have the following set of properties:
- defaultElement: An element to use when a widget instance is constructed without providing an element. For example, since the progressbar's
defaultElement
is"<div>
",$.ui.progressbar({ value: 50 })
instantiates a progressbar widget instance on a newly created<div>
. - document: A jQuery object containing the
document
that the widget's element is within. Useful if you need to interact with widgets within iframes. - element: A jQuery object containing the element used to instantiate the widget. If you select multiple elements and call
.myWidget()
, a separate widget instance will be created for each element. Therefore, this property will always contain one element. - namespace: The location on the global jQuery object that the widget's prototype is stored on. For example a
namespace
of"ui"
indicates that the widget's prototype is stored on$.ui
. - options: An object containing the options currently being used by the widget. On instantiation, any options provided by the user will automatically be merged with any default values defined in
$.myNamespace.myWidget.prototype.options
. User specified options override the defaults. - uuid: A unique integer identifier for the widget.
- version: The string version of the widget. For jQuery UI widgets this will be set to the version of jQuery UI the widget is using. Widget developers have to set this property in their prototype explicitly.
- widgetEventPrefix: The prefix prepended to the name of events fired from this widget. For example the
widgetEventPrefix
of the draggable widget is"drag"
, therefore when a draggable is created, the name of the event fired is"dragcreate"
. By default thewidgetEventPrefix
of a widget is its name. Note: This property is deprecated and will be removed in a later release. Event names will be changed to widgetName:eventName (e.g."draggable:create"
). - widgetFullName: The full name of the widget including the namespace. For
$.widget( "myNamespace.myWidget", {} )
,widgetFullName
will be"myNamespace-myWidget"
. - widgetName: The name of the widget. For
$.widget( "myNamespace.myWidget", {} )
,widgetName
will be"myWidget"
. - window: A jQuery object containing the
window
that the widget's element is within. Useful if you need to interact with widgets within iframes.
The name of the widget to create, including the namespace.
The base widget to inherit from. This must be a constructor that can be instantiated with the `new` keyword. Defaults to jQuery.Widget
.
The object to use as a prototype for the widget.
false
true
.Code examples:
Initialize the widget with the disabled
option specified:
$( ".selector" ).widget({ disabled: true });
Get or set the disabled
option, after initialization:
// Getter var disabled = $( ".selector" ).widget( "option", "disabled" ); // Setter $( ".selector" ).widget( "option", "disabled", true );
null
Multiple types supported:
- Boolean: When set to
false
, no animation will be used and the element will be hidden immediately. When set totrue
, the element will fade out with the default duration and the default easing. - Number: The element will fade out with the specified duration and the default easing.
- String: The element will be hidden using the specified effect. The value can either be the name of a built-in jQuery animation method, such as
"slideUp"
, or the name of a jQuery UI effect, such as"fold"
. In either case the effect will be used with the default duration and the default easing. - Object: If the value is an object, then
effect
,delay
,duration
, andeasing
properties may be provided. If theeffect
property contains the name of a jQuery method, then that method will be used; otherwise it is assumed to be the name of a jQuery UI effect. When using a jQuery UI effect that supports additional settings, you may include those settings in the object and they will be passed to the effect. Ifduration
oreasing
is omitted, then the default values will be used. Ifeffect
is omitted, then"fadeOut"
will be used. Ifdelay
is omitted, then no delay is used.
Code examples:
Initialize the widget with the hide
option specified:
$( ".selector" ).widget({ hide: { effect: "explode", duration: 1000 } });
Get or set the hide
option, after initialization:
// Getter var hide = $( ".selector" ).widget( "option", "hide" ); // Setter $( ".selector" ).widget( "option", "hide", { effect: "explode", duration: 1000 } );
null
Multiple types supported:
- Boolean: When set to
false
, no animation will be used and the element will be shown immediately. When set totrue
, the element will fade in with the default duration and the default easing. - Number: The element will fade in with the specified duration and the default easing.
- String: The element will be shown using the specified effect. The value can either be the name of a built-in jQuery animation method, such as
"slideDown"
, or the name of a jQuery UI effect, such as"fold"
. In either case the effect will be used with the default duration and the default easing. - Object: If the value is an object, then
effect
,delay
,duration
, andeasing
properties may be provided. If theeffect
property contains the name of a jQuery method, then that method will be used; otherwise it is assumed to be the name of a jQuery UI effect. When using a jQuery UI effect that supports additional settings, you may include those settings in the object and they will be passed to the effect. Ifduration
oreasing
is omitted, then the default values will be used. Ifeffect
is omitted, then"fadeIn"
will be used. Ifdelay
is omitted, then no delay is used.
Code examples:
Initialize the widget with the show
option specified:
$( ".selector" ).widget({ show: { effect: "blind", duration: 800 } });
Get or set the show
option, after initialization:
// Getter var show = $( ".selector" ).widget( "option", "show" ); // Setter $( ".selector" ).widget( "option", "show", { effect: "blind", duration: 800 } );
_create()
method is the widget's constructor. There are no parameters, but this.element
and this.options
are already set. - This method does not accept any arguments.
Set the background color of the widget's element based on an option.
_create: function() { this.element.css( "background-color", this.options.color ); }
this
context correct. Essentially setTimeout()
. Returns the timeout ID for use with clearTimeout()
.
- fnThe function to invoke. Can also be the name of a method on the widget.
- delayType: NumberThe number of milliseconds to wait before invoking the function. Defaults to
0
.
Call the _foo()
method on the widget after 100 milliseconds.
this._delay( this._foo, 100 );
destroy()
method cleans up all common data, events, etc. and then delegates out to _destroy()
for custom, widget-specific, cleanup. - This method does not accept any arguments.
Remove a class from the widget's element when the widget is destroyed.
_destroy: function() { this.element.removeClass( "my-widget" ); }
element
to apply the ui-state-focus
class on focus. The event handlers are automatically cleaned up on destroy.
- elementType: jQueryThe element(s) to apply the focusable behavior to.
Apply focusable styling to a set of elements within the widget.
this._focusable( this.element.find( ".my-items" ) );
create
event. By default, no data is provided in the event, but this method can return an object which will be passed as the create
event's data. - This method does not accept any arguments.
Pass the widget's options to create
event handlers as an argument.
_getCreateEventData: function() { return this.options; }
- This method does not accept any arguments.
Make the widget element's id attribute available as an option.
_getCreateOptions: function() { return { id: this.element.attr( "id" ) }; }
option
values. - elementType: jQueryThe element(s) to hide.
- optionType: ObjectThe properties defining how to hide the element.
- callbackType: Function()Callback to invoke after the element has been fully hidden.
Pass along the hide
option for custom animations.
this._hide( this.element, this.options.hide, function() { // Remove the element from the DOM when it's fully hidden. $( this ).remove(); });
element
to apply the ui-state-hover
class on hover. The event handlers are automatically cleaned up on destroy.
- elementType: jQueryThe element(s) to apply the hoverable behavior to.
Apply hoverable styling to all <div>
s within the element on hover.
this._hoverable( this.element.find( "div" ) );
Note: Initialization should only be handled if there is a logical action to perform on successive calls to the widget with no arguments.
- This method does not accept any arguments.
Call the open()
method if the autoOpen
option is set.
_init: function() { if ( this.options.autoOpen ) { this.open(); } }
- elementType: jQueryThe element(s) to unbind the event handlers from. Unlike the
_on()
method, the elements are required for_off()
. - eventNameType: StringOne or more space-separated event types.
Unbind all click events from the widget's element.
this._off( this.element, "click" );
click .foo
". The _on()
method provides several benefits of direct event binding: - Maintains proper
this
context inside the handlers. - Automatically handles disabled widgets: If the widget is disabled or the event occurs on an element with the
ui-state-disabled
class, the event handler is not invoked. Can be overridden with thesuppressDisabledCheck
parameter. - Event handlers are automatically namespaced and cleaned up on destroy.
- suppressDisabledCheck (default:
false
)Type: BooleanWhether or not to bypass the disabled check. - elementType: jQueryWhich element(s) to bind the event handlers to. If no element is provided,
this.element
is used for non-delegated events and the widget element is used for delegated events. - handlersType: ObjectAn object in which the keys represent the event type and optional selector for delegation, and the values represent a handler function to be called for the event.
Prevent the default action of all links clicked within the widget's element.
this._on( this.element, { "click a": function( event ) { event.preventDefault(); } });
_setOptions()
method for each individual option. Widget state should be updated based on changes. Update a widget's element when its height
or width
option changes.
_setOption: function( key, value ) { if ( key === "width" ) { this.element.width( value ); } if ( key === "height" ) { this.element.height( value ); } this._super( key, value ); }
option()
method is called, regardless of the form in which the option()
method was called. Overriding this is useful if you can defer processor-intensive changes for multiple option changes.
- optionsType: ObjectAn object containing options to set, with the name of the option as the key and the option value as the value.
Call a resize()
method if the height
or width
options change.
_setOptions: function( options ) { var that = this, resize = false; $.each( options, function( key, value ) { that._setOption( key, value ); if ( key === "height" || key === "width" ) { resize = true; } }); if ( resize ) { this.resize(); } }
option
values. - elementType: jQueryThe element(s) to show.
- optionType: ObjectThe properties defining how to show the element.
- callbackType: Function()Callback to invoke after the element has been fully shown.
Pass along the show
option for custom animations.
this._show( this.element, this.options.show, function() { // Focus the element when it's fully visible. this.focus(); }
.call()
. - argType: ObjectZero to many arguments to pass to the parent widget's method.
Handle title
option updates and call the parent widget's _setOption()
to update the internal storage of the option.
_setOption: function( key, value ) { if ( key === "title" ) { this.element.find( "h3" ).text( value ); } this._super( key, value ); }
.apply()
. - argumentsType: ArrayArray of arguments to pass to the parent method.
Handle title
option updates and call the parent widget's _setOption()
to update the internal storage of the option.
_setOption: function( key, value ) { if ( key === "title" ) { this.element.find( "h3" ).text( value ); } this._superApply( arguments ); }
The option with the name equal to type is invoked as the callback.
The event name is the lowercase concatenation of the widget name and type.
Note: When providing data, you must provide all three parameters. If there is no event to pass along, just pass null
.
If the default action is prevented, false
will be returned, otherwise true
. Preventing the default action happens when the handler returns false
or calls event.preventDefault()
.
- typeType: StringThe
type
should match the name of a callback option. The full event type will be generated automatically. - eventType: EventThe original event that caused this event to occur; useful for providing context to the listener.
- dataType: ObjectA hash of data associated with the event.
Trigger a search
event whenever a key is pressed.
this._on( this.element, { keydown: function( event ) { // Pass the original event so that the custom search event has // useful information, such as keyCode this._trigger( "search", event, { // Pass additional information unique to this event value: this.element.val() }); } });
- This method does not accept any arguments.
- This method does not accept any arguments.
- This method does not accept any arguments.
Retrieves the widget's instance object. If the element does not have an associated instance, undefined
is returned.
Unlike other widget methods, instance()
is safe to call on any element after the widget plugin has loaded.
- This method does not accept any arguments.
Gets the value currently associated with the specified optionName
.
Note: For options that have objects as their value, you can get the value of a specific key by using dot notation. For example, "foo.bar"
would get the value of the bar
property on the foo
option.
- optionNameType: StringThe name of the option to get.
- This signature does not accept any arguments.
Sets the value of the widget option associated with the specified optionName
.
Note: For options that have objects as their value, you can set the value of just one property by using dot notation for optionName
. For example, "foo.bar"
would update only the bar
property of the foo
option.
- optionNameType: StringThe name of the option to set.
- valueType: ObjectA value to set for the option.
- optionsType: ObjectA map of option-value pairs to set.
jQuery
object containing the original element or other relevant generated element. - This method does not accept any arguments.
widgetcreate
Note: The ui
object is empty but included for consistency with other events.
Initialize the widget with the create callback specified:
$( ".selector" ).widget({ create: function( event, ui ) {} });
Bind an event listener to the widgetcreate event:
$( ".selector" ).on( "widgetcreate", function( event, ui ) {} );
Please login to continue.