Easy Tutorial
❮ Example Addclass Example Toggle ❯

jQuery UI API - Widget Factory

Category

Utilities | Widgets

jQuery.widget( name [, base ], prototype ) Usage

Description: Create stateful jQuery plugins using the same abstraction as all jQuery UI widgets.

Parameter Type Description
name String The name of the widget to create, including the namespace.
base Function() The base widget to inherit from. This must be a constructor that can be instantiated with the new keyword. Defaults to jQuery.Widget.
prototype PlainObject The object to use as the widget prototype.

You can use the $.Widget object as the base to inherit from, or you can explicitly inherit from existing jQuery UI or third-party widgets and create new widgets from scratch. Defining a widget with the same name to inherit from the base widget allows you to extend the widget appropriately.

jQuery UI contains many stateful widgets, so it uses a slightly different pattern than typical jQuery plugins. All jQuery UI widgets use the same pattern, which is defined by the Widget Factory. So, once you learn to use one widget, you know how to use the others.

Note: This section uses the Progressbar Widget to demonstrate examples, but the syntax applies to every widget.

Initialization

To keep track of the state of the widget, we need to introduce the full life cycle of 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 the example above, the element has the id "elem".

Options

Since the progressbar() call is made without arguments, the widget is initialized with the default options. We can pass a set of options during initialization to override the defaults:

$( "#elem" ).progressbar({ value: 20 });

You can pass as many options as you like, and any options you do not pass will use their default values.

You can pass multiple option arguments, and they will be merged into a single object (similar to $.extend( true, target, object1, objectN )). This is useful for overriding some settings for all instances and sharing options between instances:

var options = { modal: true, show: "slow" };
$( "#dialog1" ).dialog( options );
$( "#dialog2" ).dialog( options, { autoOpen: false });

All options passed during initialization are deep-copied, ensuring that subsequent modifications to the object do not affect the widget. Arrays are the only exception, as they are referenced as-is. This exception is to support data binding properly, where the data source must be referenced.

Default values are stored in the widget's property, so we can override the values set by jQuery UI. For example, after the following setting, all future progressbar instances will default to a value of 80:

$.ui.progressbar.prototype.options.value = 80;

Options are part of the widget's state, so we can also set options after initialization. We will see the option method later.

Methods

Now that the widget is initialized, we can query its state or perform actions on the widget. All actions after initialization are performed as method calls. 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 the Progressbar Widget, we use:

$( "#elem" ).progressbar( "value" );

If the method accepts arguments, we pass them after the method name. For example, to pass the argument 40 to the value() method, we use:

$( "#elem" ).progressbar( "value", 40 );

Like other methods in jQuery, most widget methods return the jQuery object:

$( "#elem" )
  .progressbar( "value", 90 )
  .addClass( "almost-done" );

Each widget has its own method settings, which are based on the functionality provided by the widget. However, there are some methods that exist on all widgets, which will be explained in detail below.

Events

All widgets have events related to their various behaviors to notify you when their state changes. For most widgets, when an event is triggered, the name is prefixed with the lowercase name of the widget. For example, we can bind the change event of a progress bar, which is triggered when the value changes.

$( "#elem" ).bind( "progressbarchange", function() {
  alert( "The value has changed!" );
});

Each event has a corresponding callback, which serves as an option. If needed, we can catch the change callback of the progress bar without binding the progressbarchange event.

$( "#elem" ).progressbar({
  change: function() {
    alert( "The value has changed!" );
  }
});

All widgets have a change event that is triggered upon instantiation.

Instantiation

Widget instances are stored using the full widget name as the key with jQuery.data(). Therefore, you can retrieve the instance object of the Progressbar Widget from the element using the following code.

$( "#elem" ).data( "ui-progressbar" );

To check if an element is bound to a given widget, you can use the :data selector.

$( "#elem" ).is( ":data( 'ui-progressbar' )" ); // true
$( "#elem" ).is( ":data( 'ui-draggable' )" ); // 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 properties:

-window: The window that contains the widget element. Useful when interaction with the widget is needed within a frame.

jQuery.Widget Basic Widget Usage

Description: The base widget used by the Widget Factory.

Quick Navigation

Options Methods Events
disabled hide show _create _delay _destroy _focusable _getCreateEventData _getCreateOptions _hide _hoverable _init _off _on _setOption _setOptions _show _super _superApply _trigger destroy disable enable option widget create
Option Type Description Default Value
disabled Boolean If set to true, the widget is disabled. <br> Code example: Initialize the widget with the specified disabled option: $( ".selector" ).widget({ disabled: true }); After initialization, get or set the disabled option: // getter<br>var disabled = $( ".selector" ).widget( "option", "disabled" );<br> <br>// setter<br>$( ".selector" ).widget( "option", "disabled", true ); false
hide Boolean or Number or String or Object Whether to animate the hiding of the element and how. <br> Supports multiple types: Boolean: When set to false, no animation is used and the element is hidden immediately. When set to true, the element fades out using the default duration and default easing.<br> Number: The element will fade out using the specified duration and default easing.<br> String: The element will hide using the specified effect. The value can be a built-in jQuery animation method name, such as "slideUp", or a jQuery UI effect name, such as "fold". Both cases will use the default duration and default easing.<br> Object: If the value is an object, the effect, delay, duration, and easing properties are provided. If the effect property contains the name of a jQuery method, that method is used; otherwise, it is considered the name of a jQuery UI effect. When using a jQuery UI effect that supports additional settings, you can include those settings in the object, and they will be passed to the effect. If duration or easing is omitted, the default values are used. If effect is omitted, "fadeOut" is used. If delay is omitted, no delay is used. Code example: Initialize the widget with the specified hide option: $( ".selector" ).widget({ hide: { effect: "explode", duration: 1000 } }); After initialization, get or set the hide option: // getter<br>var hide = $( ".selector" ).widget( "option", "hide" );<br> <br>// setter<br>$( ".selector" ).widget( "option", "hide", { effect: "explode", duration: 1000 } ); null
show Boolean or Number or String or Object Whether to animate the display of elements and how to animate them. <br> Supports multiple types: Boolean: When set to false, no animation is used and the element is displayed immediately. When set to true, the element fades in with the default duration and default easing. <br> Number: The element will fade in with the specified duration and default easing. <br> String: The element will be displayed using the specified effect. The value can be a built-in jQuery animation method name, such as "slideDown", or a jQuery UI effect name, such as "fold". Both cases will use the default duration and default easing. <br> Object: If the value is an object, the properties effect, delay, duration, and easing will be provided. If the effect property contains the name of a jQuery method, that method is used; otherwise, it is considered a jQuery UI effect name. When using a jQuery UI effect that supports additional settings, you can include these settings in the object, and they will be passed to the effect. If duration or easing is omitted, the default values are used. If effect is omitted, "fadeIn" is used. If delay is omitted, no delay is used. Code example: Initialize the widget with the specified show option: $( ".selector" ).widget({ show: { effect: "blind", duration: 800 } }); After initialization, get or set the show option: // getter<br>var show = $( ".selector" ).widget( "option", "show" );<br> <br>// setter<br>$( ".selector" ).widget( "option", "show", { effect: "blind", duration: 800 } ); null
Method Return Description
_create() jQuery (plugin only) The _create() method is the constructor for the widget. No parameters are accepted, but this.element and this.options are already set. <br> This method does not accept any parameters. Code example: Set the background color of the widget element based on an option. _create: function() {<br> this.element.css( "background-color", this.options.color );<br>}
_delay( fn [, delay ] ) Number Calls the provided function after the specified delay. Maintains the correct this context. Essentially a setTimeout(). <br> Returns the timeout ID for use with clearTimeout(). <br> fn<br> Type: Function() or String<br> Description: The function to call. Can also be the name of a method on the widget. <br> delay<br> Type: Number<br> Description: The number of milliseconds to wait before calling the function, default is 0. Code example: Call the _foo() method on the widget after 100 milliseconds. this._delay( this._foo, 100 );
_destroy() jQuery (plugin only) Public destroy() method. <br> This method does not accept any parameters. Code example: Remove a class from the widget's element when the widget is destroyed. _destroy: function() {<br> this.element.removeClass( "my-widget" );<br>}
_focusable( element ) jQuery (plugin only) Applies the ui-state-focus class to the element when it is focused. <br> element<br> Type: jQuery<br> Description: The element to apply the focusable behavior to. Code example: Apply focusable styling to a set of elements within the widget: this._focusable( this.element.find( ".my-items" ) );
_getCreateEventData() Object All widget trigger create event data is passed. <br> This method does not accept any parameters. Code example: Pass the widget's options to the create event handler as a parameter. _getCreateEventData: function() {<br> return this.options;<br>}
_getCreateOptions() Object This method allows the widget to define a custom method for defining options during initialization. User-provided options will override the options returned by this method, i.e., they will override the default options. <br> This method does not accept any parameters. Code example: Make the widget element's id attribute available as an option. _getCreateOptions: function() {<br> return { id: this.element.attr("id") };<br>}
_hide( element, option [, callback ] ) jQuery (plugin only) Hide an element using built-in animation methods or custom effects. For possible option values, see hide <br> element<br> Type: jQuery<br> Description: The element to hide.<br> <br> option<br> Type: Object<br> Description: Settings that define how to hide the element.<br> <br> callback<br> Type: Function()<br> Description: A callback to call after the element is fully hidden. Code example: Pass hide options for custom animation. this._hide( this.element, this.options.hide, function() {<br> <br> // Remove the element from the DOM when it's fully hidden.<br> $(this).remove();<br>});
_hoverable( element ) jQuery (plugin only) Establish an element to apply the ui-state-hover class when hovering over it. Event handlers are automatically cleaned up on destruction. <br> element<br> Type: jQuery<br> Description: The element to apply the hoverable behavior. Code example: Apply hoverable styling to all divs inside the element when hovering over it. this._hoverable( this.element.find("div") );
_init() jQuery (plugin only) The widget's initialization concept differs from creation. Any time the plugin is called without parameters or with only an options hash, the widget is initialized. This method is included when the widget is created. Note: Initialization can only handle logic actions to be performed when the widget is successfully called without parameters. This method does not accept any parameters. Code example: Call the open() method if the autoOpen option is set. _init: function() {<br> if (this.options.autoOpen) {<br> this.open();<br> }<br>}
_off( element, eventName ) jQuery (plugin only) Unbind event handlers from the specified element. <br> element<br> Type: jQuery<br> Description: The element to unbind event handlers from. Unlike the _on() method, the element is required in the _off() method.<br> <br> eventName<br> Type: String<br> Description: One or more space-separated event types. Code example: Unbind all click events from the widget's element. this._off( this.element, "click" );
_on( [suppressDisabledCheck ] [, element ], handlers ) jQuery (plugin only) The selector within the event name is supported for authorization, such as "click .foo". The _on() method provides some benefits of direct event binding: <br> Maintains proper this context within handlers. <br> 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 called. This can be overridden by the suppressDisabledCheck parameter. <br> Event handlers are automatically namespaced and cleaned up upon destruction. <br> suppressDisabledCheck (default: false) <br> Type: Boolean <br> Description: Whether to bypass the disabled check. <br> element <br> Type: jQuery <br> Description: The element to bind the event handler to. If not provided, this.element is used for unauthorized events, and the widget element for authorized events. <br> handlers <br> Type: Object <br> Description: A map where string keys represent event types, optional selectors for authorization, and values represent the handler functions called by the event. Code example: Prevent the default action for all links clicked within the widget element. this._on( this.element, { <br> "click a": function( event ) { <br> event.preventDefault(); <br> } <br> });
_setOption( key, value ) jQuery (plugin only) Calls _setOptions() for each individual option. <br> key <br> Type: String <br> Description: The name of the option to set. <br> value <br> Type: Object <br> Description: The value to set for the option. Code example: Update the widget element when the height or width options change. _setOption: function( key, value ) { <br> if ( key === "width" ) { <br> this.element.width( value ); <br> } <br> if ( key === "height" ) { <br> this.element.height( value ); <br> } <br> this._super( key, value ); <br> }
_setOptions( options ) jQuery (plugin only) Called when option() is invoked. Overloading this method is useful if you want to respond to changes in multiple options. <br> options <br> Type: Object <br> Description: The values to set for the options. Code example: Call the resize method if the height or width options change. _setOptions: function( options ) { <br> var that = this, <br> resize = false; <br> $.each( options, function( key, value ) { <br> that._setOption( key, value ); <br> if ( key === "height" key === "width" ) { <br> resize = true; <br> } <br> }); <br> if ( resize ) { <br> this.resize(); <br> } <br> }
_show( element, option [, callback ] ) jQuery (plugin only) Use built-in animation methods or custom effects to show an element. For possible option values, see show <br> element<br> Type: jQuery<br> Description: The element to be shown.<br> <br> option<br> Type: Object<br> Description: Settings that define how the element is shown.<br> <br> callback<br> Type: Function()<br> Description: A callback to be called after the element is fully shown. Code example: Pass show options for custom animation. this._show( this.element, this.options.show, function() {<br> <br> // Focus the element when it's fully visible.<br> this.focus();<br>}
_super( [arg ] [, ... ] ) jQuery (plugin only) Call a method with the same name from the parent widget, with any specified arguments. Essentially .call(). <br> arg<br> Type: Object<br> Description: Zero to multiple arguments to pass to the parent widget's method. Code example: Handle title option updates and call the parent widget's _setOption() to update the internal storage of the option. _setOption: function( key, value ) {<br> if ( key === "title" ) {<br> this.element.find( "h3" ).text( value );<br> }<br> this._super( key, value );<br>}
_superApply( arguments ) jQuery (plugin only) Call a method with the same name from the parent widget, with an array of arguments. Essentially .apply(). <br> arguments<br> Type: Array<br> Description: An array of arguments to pass to the parent widget's method. Code example: Handle title option updates and call the parent widget's _setOption() to update the internal storage of the option. _setOption: function( key, value ) {<br> if ( key === "title" ) {<br> this.element.find( "h3" ).text( value );<br> }<br> this._superApply( arguments );<br>}
_trigger( type [, event ] [, data ] ) Boolean Trigger an event and its associated callback. The option with the same name as the type is called as a callback. <br> The event name is a lowercase string of the widget name and type. Note: When providing data, you must provide all three parameters. If no event is passed, pass null. Returns false if the default behavior is prevented, otherwise returns true. Default behavior is prevented when the handler returns false or calls event.preventDefault(). type<br> Type: String<br> Description: The type should match the name of the callback option. The full event type is generated automatically.<br> <br> event<br> Type: Event<br> Description: The original event that caused this event, useful for providing context to listeners.<br> <br> data<br> Type: Object<br> Description: A hash of data related to the event. Code example: Trigger a search event when a key is pressed. this._on( this.element, {<br> keydown: function( event ) {<br> <br> // Pass the original event so that the custom search event has<br> // useful information, such as keyCode<br> this._trigger( "search", event, {<br> <br> // Pass additional information unique to this event<br> value: this.element.val()<br> });<br> }<br>});
destroy() jQuery (plugin only) Completely removes the widget functionality. This will return the element to its pre-init state. <br> This method does not accept any parameters. Code example: Destroy the widget when any anchor within the widget is clicked. this._on( this.element, {<br> "click a": function( event ) {<br> event.preventDefault();<br> this.destroy();<br> }<br>});
disable() jQuery (plugin only) Disables the widget. <br> This method does not accept any parameters. Code example: Disable the widget when any anchor within the widget is clicked. this._on( this.element, {<br> "click a": function( event ) {<br> event.preventDefault();<br> this.disable();<br> }<br>});
enable() jQuery (plugin only) Enables the widget. <br> This method does not accept any parameters. Code example: Enable the widget when any anchor within the widget is clicked. this._on( this.element, {<br> "click a": function( event ) {<br> event.preventDefault();<br> this.enable();<br> }<br>});
option( optionName ) Object Gets the value currently associated with the specified optionName. <br> optionName<br> Type: String<br> Description: The name of the option to get. Code example: Get the value of the width option. this.option( "width" );
option() PlainObject Gets an object containing key/value pairs representing the current widget options hash. <br> This method does not accept any parameters. Code example: Log key/value pairs for each widget option for debugging. var options = this.option();<br>for ( var key in options ) {<br> console.log( key, options[ key ] );<br>}
option( optionName, value ) jQuery (plugin only) Sets the value of the widget option associated with the specified optionName. <br> optionName<br> Type: String<br> Description: The name of the option to set.<br> <br> value<br> Type: Object<br> Description: The value to set for the option. Code example: Set the width option to 500. this.option( "width", 500 );
option( options ) jQuery (plugin only) Sets one or more options for the widget. <br> options<br> Type: Object<br> Description: A map of option-value pairs to set. Code example: Set the height and width options to 500. this.option({<br> width: 500,<br> height: 500<br>});
widget() jQuery Returns a jQuery object containing the original element or other related generated elements. <br> This method does not accept any parameters. Code example: Place a red border around the original element of the widget when the widget is created. _create: function() {<br> this.widget().css( "border", "2px solid red" );<br>}
Event Type Description
create( event, ui ) widgetcreate Triggered when the widget is created. <br> event<br> Type: Event<br> <br> ui<br> Type: Object Note: The ui object is empty, including it here for consistency with other events. Code example: Initialize the widget with a specified create callback: $( ".selector" ).widget({<br> create: function( event, ui ) {}<br>}); Bind an event listener to the widgetcreate event: $( ".selector" ).on( "widgetcreate", function( event, ui ) {} );
❮ Example Addclass Example Toggle ❯