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.

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

Parameters Type Type
name String The name of the widget to create, including the namespace.
base Function() The base widget to inherit from. 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$.Widgetan object as the base to inherit from, or you can explicitly create a new widget from scratch based on an existing jQuery UI or third-party control. Defining a widget with the same name to inherit the base widget even allows you to extend the widget appropriately.

jQuery UI contains many stateful widgets, so the usage pattern is slightly different from typical jQuery plugins. All jQuery UI widgets use the same pattern, defined by the Widget Factory. So once you learn to use one, you know how to use the other widgets.

Note: This chapter uses theProgressbar Widgetas a demonstration example, but the syntax applies to every widget.

Initialization

In order to track the state of the widget, we must introduce the full lifecycle of the widget. The lifecycle begins when the widget is initialized. To initialize a widget, we simply call the plugin on one or more elements.

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

This initializes each element in the jQuery object. In the example above, the element id is `progressbar`."elem"。

Options

Becauseprogressbar()it is called without arguments, the widget is initialized with default options. We can pass a set of options at initialization to override the default options:

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

We can pass as many options as needed, and any options we do not pass use their default values.

You can pass multiple option arguments, which will be merged into a single object (similar to$.extend( true, target, object1, objectN )`$.extend`). 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 at initialization are deep copied, ensuring that objects can be modified later without affecting the widget. Arrays are the only exception; they are referenced as-is. This exception is to properly support data binding, where the data source must be a reference.

Default values are stored in the widget's properties, 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 an integral 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 has been initialized, we can query its state or perform actions on the widget. All actions after initialization are performed by calling methods. To call a method on the widget, we pass the method name to the jQuery plugin. For example, to call thevalue()`value` method, we can use:

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

If a method accepts parameters, we can pass them after the method name. For example, to pass the parameter `2` to the40tovalue()`value` method, we can 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 set of methods based on the functionality provided by the widget. However, there are some methods that exist on all widgets, which are explained in detail below.

Events

All widgets have events associated with their various behaviors to notify you when state changes. For most widgets, when an event is triggered, its name is prefixed with the lowercase form of the widget name. For example, we can bind the progressbar'schange`change` event, which is triggered when the value changes.

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

Each event has a corresponding callback, which is available as an option. If needed, we can hook into the progressbar'schange`change` callback instead of bindingprogressbarchangethe `change` event.

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

All widgets have achange`create` event, which is triggered upon instantiation.

Instantiation

The widget instance is stored using the widget's full name as the key injQuery.data()`data`. Therefore, you can use the following code to retrieve the instance object of the Progressbar Widget from an element.

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

Whether an element is bound to a given widget can be detected using the:data`:ui-progressbar` selector.

$( "#elem" ).is( ":data( 'ui-progressbar' )" ); // true
$( "#elem" ).is( ":data( 'ui-draggable' )" ); // false

You can also use:datato obtain a list of all elements that are instances of a given widget.

$( ":data( 'ui-progressbar' )" );

Properties

All widgets have the following properties:

  • defaultElement`defaultElement`: The element to use when no element was provided when constructing the widget instance. For example, since the progressbar'sdefaultElementYes"<div>",$.ui.progressbar({ value: 50 })`defaultElement` is a newly created<div>`div`, you can instantiate a progressbar widget instance without passing an element.
  • document`document`: The document that contains the widget's element.documentUseful if you need to interact with the widget within an iframe.
  • element`element`: A jQuery object containing the element used to instantiate the widget. If you select multiple elements and call.myWidget()`.progressbar()`, a separate widget instance will be created for each element. Therefore, this property always contains one element.
  • namespace`namespace`: The location in the global jQuery object where the widget prototype is stored. For example,"ui"ofnamespace`$.ui.draggable` indicates that the widget prototype is stored in$.ui。
  • options`$.ui.draggable`. `options`: An object containing the options currently used by the widget. At instantiation, any user-provided options will automatically be merged with$.myNamespace.myWidget.prototype.optionsthe default values defined in the widget prototype. User-specified options override the defaults.
  • uuid`uuid`: A unique integer representing the widget identifier.
  • version`version`: The string version of the widget. For jQuery UI widgets, this property is set to the version of jQuery UI used by the widget. Plugin developers must explicitly set this property in their prototypes.
  • widgetEventPrefix`widgetEventPrefix`: The prefix added to the widget's event names. For example,the Draggable WidgetofwidgetEventPrefixYes"drag", so when creating a draggable, the event name is"dragcreate"`dragcreate`. By default, the widget'swidgetEventPrefix`widgetEventPrefix` is its name.Note: This property has been deprecated and will be removed in future versions. Event names will be changed to widgetName:eventName (for example `progressbarcreate`)."draggable:create")。
  • widgetFullName`widgetFullName`: The full name of the widget, including the namespace. For$.widget( "myNamespace.myWidget", {} ), widgetFullNamethe progressbar, this will be `ui-progressbar`."myNamespace-myWidget"。
  • widgetName`name`: The name of the widget. For$.widget( "myNamespace.myWidget", {} ),widgetNamethe progressbar, this will be `progressbar`."myWidget"。
  • window`window`: The window that contains the widget's element.windowUseful if you need to interact with the widget within an iframe.

jQuery.Widget Base Widget Usage

Description:The base widget used by the Widget Factory.

Quick Navigation

Options Methods Events

Options Type Description Default
disabled Boolean If set totrue`true`, the widget is disabled.

Code examples:

Initialize a widget with the specifieddisabled`disabled` option:

$( ".selector" ).widget({ disabled: true });
    

Get or set thedisabled`disabled` option after initialization:

// getter
var disabled = $( ".selector" ).widget( "option", "disabled" );
 
// setter
$( ".selector" ).widget( "option", "disabled", true );
    
false
hide Boolean or Number or String or Object Whether and how to use animation to hide the element.

Multiple types are supported:

  • Boolean: When set tofalse`false`, no animation is used and the element is hidden immediately. When set totrue`true`, the element fades out with the default duration and default easing.
  • Number: The element fades out with the specified duration and default easing.
  • String: The element is hidden using the specified effect. The value can be a built-in jQuery animation method name, such as"slideUp"`slideUp`, or ajQuery UI effectname, such as"fold"For both of the above cases, the effect uses the default duration and the default easing.
  • Object: If the value is an object, theneffect、delay、durationandeasingproperty is provided. Ifeffectproperty contains the name of a jQuery method, that method is used; otherwise, it is considered to be 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. Ifdurationoreasingis omitted, the default value is used. Ifeffectis omitted, then"fadeOut". Ifdelayis omitted, no delay is used.

Code examples:

Initialize the widget with the specifiedhideoption:

$( ".selector" ).widget({ hide: { effect: "explode", duration: 1000 } });
    

After initialization, get or set thehideoption:

// getter
var hide = $( ".selector" ).widget( "option", "hide" );
 
// setter
$( ".selector" ).widget( "option", "hide", { effect: "explode", duration: 1000 } );
    
null
show Boolean or Number or String or Object Whether to display the element with an animation, and how to animate the display.

Supports multiple types:

  • Boolean: When set tofalse, no animation is used, and the element is displayed immediately. When set totrue, the element fades in using the default duration and default easing.
  • Number: The element fades in using the specified duration and the default easing.
  • String: The element will be displayed using the specified effect. The value can be the name of a built-in jQuery animation method, such as"slideDown", or it can be ajQuery UI effectname, such as"fold". For both of the above cases, the effect uses the default duration and default easing.
  • Object: If the value is an object, theneffect、delay、durationandeasingproperty is provided. Ifeffectproperty contains the name of a jQuery method, that method is used; otherwise, it is considered to be 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. Ifdurationoreasingis omitted, the default value is used. Ifeffectis omitted, then"fadeIn". Ifdelayis omitted, no delay is used.

Code examples:

Initialize the widget with the specifiedshowoption:

$( ".selector" ).widget({ show: { effect: "blind", duration: 800 } });
    

After initialization, get or set theshowoption:

// getter
var show = $( ".selector" ).widget( "option", "show" );
 
// setter
$( ".selector" ).widget( "option", "show", { effect: "blind", duration: 800 } );
    
null

Methods Returns Description
_create() jQuery (plugin only) _create()method is the widget's constructor. It takes no arguments, butthis.elementandthis.optionsis already set.
  • This method accepts no arguments.

Code examples:

Sets the background color of the widget element based on an option.

_create: function() {
  this.element.css( "background-color", this.options.color );
}
    
_delay( fn [, delay ] ) Number Calls the provided function after the specified delay. Maintainsthisthe correct context. EssentiallysetTimeout()。
usesclearTimeout()returns the timeout ID.
  • fn
    Type: Function() or String
    Description: The function to call. It can also be the name of a method on the widget.
  • delay
    Type: Number
    Description: The number of milliseconds to wait before calling the function. Defaults to0。

Code examples:

After 100 milliseconds, on the widget, call the_foo()method.

this._delay( this._foo, 100 );
    
_destroy() jQuery (plugin only) The publicdestroy()method clears all public data, events, etc. It represents the custom, widget-specific cleanup._destroy()。
  • This method accepts no arguments.

Code examples:

Removes a class from the widget's element when the widget is destroyed.

_destroy: function() {
  this.element.removeClass( "my-widget" );
}
    
_focusable( element ) jQuery (plugin only) Establishes, when focusing on an element, theui-state-focusclass to be applied.element。
  • element
    Type: jQuery
    Description: The element to apply the focusable behavior to.

Code examples:

Applies focusable styling to a group of elements within the widget:

this._focusable( this.element.find( ".my-items" ) );
    
_getCreateEventData() Object All widgets triggercreateevents. By default, no data is provided in the event, but this method returns an object that is passed ascreateevent data.
  • This method accepts no arguments.

Code examples:

towardcreateThe event handler passes the widget's options as an argument.

_getCreateEventData: function() {
  return this.options;
}
    
_getCreateOptions() Object This method allows the widget to define a custom method for defining options during initialization. User-provided options override the options returned by this method, i.e., they override the default options.
  • This method accepts no arguments.

Code examples:

Makes the id attribute of the widget's element available as an option.

_getCreateOptions: function() {
  return { id: this.element.attr( "id" ) };
}
    
_hide( element, option [, callback ] ) jQuery (plugin only) Hides an element using a built-in animation method or a custom effect. For possibleoptionvalues, seehide。
  • element
    Type: jQuery
    Description: The element to hide.
  • option
    Type: Object
    Description: Settings that define how to hide the element.
  • callback
    Type: Function()
    Description: A callback to call after the element is completely hidden.

Code examples:

Passeshideoptions for the custom animation.

this._hide( this.element, this.options.hide, function() {
 
  // Remove the element from the DOM when it's fully hidden.
  $( this ).remove();
});
    
_hoverable( element ) jQuery (plugin only) Establishes, when hovering over an element, theui-state-hoverclass to be applied.element. Event handlers are automatically cleaned up on destroy.
  • element
    Type: jQuery
    Description: The element to apply the hoverable behavior to.

Code examples:

When hovering over the element, to all elements within the element,divapply hoverable styling.

this._hoverable( this.element.find( "div" ) );
    
_init() jQuery (plugin only) The concept of widget initialization is different from creation. Whenever the plugin is called without arguments or with only an options hash, the widget is initialized. This method is included when the widget is created.

Note: If there are logical actions to be performed when the widget is successfully called without arguments, initialization can only be handled at this time.

  • This method accepts no arguments.

Code examples:

If theautoOpenoption is set, then call theopen()method.

_init: function() {
  if ( this.options.autoOpen ) {
    this.open();
  }
}
    
_off( element, eventName ) jQuery (plugin only) Unbinds event handlers from the specified element.
  • element
    Type: jQuery
    Description: The element to unbind event handlers from. Unlike the_on()method,_off()an element is required in the method.
  • eventName
    Type: String
    Description: One or more space-separated event types.

Code examples:

Unbinds all click events from the widget's element.

this._off( this.element, "click" );
    
_on( [suppressDisabledCheck ] [, element ], handlers ) jQuery (plugin only) Delegation via selectors within the event name is supported, for example"click .foo"。_on()The method provides several benefits over direct event binding:
  • Maintains the appropriatethiscontext within handlers.
  • Automatically handles disabled widgets: if the widget is disabled or the event occurs on an element with theui-state-disabledclass, the event handler is not called. Can be overridden by thesuppressDisabledCheckparameter.
  • Event handlers are automatically namespaced and automatically cleaned up on destroy.
  • suppressDisabledCheck(default:false)
    Type: Boolean
    Description: Whether to bypass the disabled check.
  • element
    Type: jQuery
    Description: The element to bind the event handlers to. If no element is provided,this.elementit is used for non-delegated events,the widget elementis used for delegated events.
  • handlers
    Type: Object
    Description: A map in which string keys represent event types, optional selectors are used for delegation, and values represent the handler functions called for the events.

Code examples:

Prevents the default behavior of all clicked links within the widget element.

this._on( this.element, {
  "click a": function( event ) {
    event.preventDefault();
  }
});
    
_setOption( key, value ) jQuery (plugin only) For each individual option, calls the_setOptions()method. The widget state is updated as changes are made.
  • key
    Type: String
    Description: The name of the option to set.
  • value
    Type: Object
    Description: The value to set for the option.

Code examples:

When the widget'sheightorwidthoption changes, update the widget's element.

_setOption: function( key, value ) {
  if ( key === "width" ) {
    this.element.width( value );
  }
  if ( key === "height" ) {
    this.element.height( value );
  }
  this._super( key, value );
}
    
_setOptions( options ) jQuery (plugin only) When theoption()method is called, regardless of the form in which it is calledoption(). If you need to change processor-intensive handlers based on multiple option changes, overriding this method is useful.
  • options
    Type: Object
    Description: The value to set for the option.

Code examples:

If the widget'sheightorwidthoption changes, call theresizemethod.

_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();
  }
}
    
_show( element, option [, callback ] ) jQuery (plugin only) Shows an element using a built-in animation method or a custom effect. For possibleoptionvalues, seeshow。
  • element
    Type: jQuery
    Description: The element to show.
  • option
    Type: Object
    Description: Settings that define how to show the element.
  • callback
    Type: Function()
    Description: A callback to be called after the element is fully displayed.

Code example:

Pass a custom animationshowoption.

this._show( this.element, this.options.show, function() {
 
  // Focus the element when it's fully visible.
  this.focus();
}
    
_super( [arg ] [, ... ] ) jQuery (plugin only) Calls the method of the same name on the parent widget, with any specified arguments. Essentially,.call()。
  • arg
    Type: Object
    Description: Zero or more arguments to pass to the parent widget's method.

Code example:

Handletitleoption updates, and call the parent widget's_setOption()to update the internal storage of the options.

_setOption: function( key, value ) {
  if ( key === "title" ) {
    this.element.find( "h3" ).text( value );
  }
  this._super( key, value );
}
    
_superApply( arguments ) jQuery (plugin only) Calls the method of the same name on the parent widget, with an array of arguments. Essentially,.apply()。
  • arguments
    Type: Array
    Description: An array of arguments to pass to the parent widget's method.

Code example:

Handletitleoption updates, and call the parent widget's_setOption()to update the internal storage of the options.

_setOption: function( key, value ) {
  if ( key === "title" ) {
    this.element.find( "h3" ).text( value );
  }
  this._superApply( arguments );
}
    
_trigger( type [, event ] [, data ] ) Boolean Trigger an event and its associated callback. The option with that name is equivalent to the type called as the callback.

The event name is a lowercase string of the widget name and the type.

Note: When data is provided, you must provide all three parameters. If no event is passed, passnull。

If the default behavior is prevented, it returnsfalse, otherwise it returnstrue. When the handler returnsfalseor callsevent.preventDefault(), the default behavior is prevented.

  • type
    Type: String
    Description:typeThe name should match the callback option. The full event type is generated automatically.
  • event
    Type: Event
    Description: The original event that caused this event to occur, useful for providing context to listeners.
  • data
    Type: Object
    Description: A data hash associated with the event.

Code example:

When a key is pressed, trigger thesearchevent.

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()
    });
  }
});
    
destroy() jQuery (plugin only) Completely remove the widget functionality. This returns the element to its pre-initialization state.
  • This method accepts no arguments.

Code example:

Destroy the widget when any anchor of the widget is clicked.

this._on( this.element, {
  "click a": function( event ) {
    event.preventDefault();
    this.destroy();
  }
});
    
disable() jQuery (plugin only) Disable the widget.
  • This method accepts no arguments.

Code example:

Disable the widget when any anchor of the widget is clicked.

this._on( this.element, {
  "click a": function( event ) {
    event.preventDefault();
    this.disable();
  }
});
    
enable() jQuery (plugin only) Enable the widget.
  • This method accepts no arguments.

Code example:

Enable the widget when any anchor of the widget is clicked.

this._on( this.element, {
  "click a": function( event ) {
    event.preventDefault();
    this.enable();
  }
});
    
option( optionName ) Object Gets the value currently associated with the specifiedoptionNameassociated value.
  • optionName
    Type: String
    Description: The name of the option to get.

Code example:

Get thewidthoption's value.

this.option( "width" );
    
option() PlainObject Gets an object containing key/value pairs that represent the current widget options hash.
  • This method accepts no arguments.

Code example:

Log the key/value pairs of each widget option for debugging.

var options = this.option();
for ( var key in options ) {
  console.log( key, options[ key ] );
}
    
option( optionName, value ) jQuery (plugin only) Sets, with the specifiedoptionNamethe value of the associated widget option.
  • optionName
    Type: String
    Description: The name of the option to set.
  • value
    Type: Object
    Description: The value to set for the option.

Code example:

Set thewidthoption to500。

this.option( "width", 500 );
    
option( options ) jQuery (plugin only) Set one or more options for the widget.
  • options
    Type: Object
    Description: The option-value pairs to set.

Code example:

Set theheightandwidthoption to500。

this.option({
  width: 500,
  height: 500
});
    
widget() jQuery Returns an object containing the original element or other related generated elementsjQueryobject.
  • This method accepts no arguments.

Code example:

When the widget is created, place a red border around the widget's original element.

_create: function() {
  this.widget().css( "border", "2px solid red" );
}
    

Events Type Description
create( event, ui ) widgetcreate Triggered when the widget is created.
  • event
    Type: Event
  • ui
    Type: Object

Note:uiThe object is empty; it is included here for consistency with other events.

Code example:

Initialize the widget with the specified create callback:

$( ".selector" ).widget({
  create: function( event, ui ) {}
});
    

Bind an event listener to the widgetcreate event:

$( ".selector" ).on( "widgetcreate", function( event, ui ) {} );
    
Other extensions