Widget Factory

jQuery

Widget Factory


Contents:

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

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

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

    • name
      Type: String
      The name of the widget to create, including the namespace.
    • base
      Type: 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
      The object to use as a prototype for the widget.

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.

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 initalized. To initialize a widget, we simply call the plugin on one or more elements.

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

This will initialize each element in the jQuery object, in this case the element with an id of "elem". Because we called the progressbar() method with no parameters, the widget is initialized with its default options. We can pass a set of options during initialization in order to override the default options.

1
                                
$( "#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.

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:

1
                                
$( "#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:

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

Just like other methods in jQuery, most widget methods return the jQuery object for chaining.

1
2
3
                                
$( "#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. For example, we can bind to progressbar's change event which is triggered whenever the value changes.

1
2
3
                                
$( "#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.

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

All widgets have a create event which is triggered upon instantiation.

Base Widget

Description: The base widget used by the widget factory.

QuickNav

Options

Events

Options

disabledType: Boolean

Default: false
Disables the widget if set to true.
Code examples:

Initialize the widget with the disabled option specified:

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

Get or set the disabled option, after initialization:

1
2
3
4
5
                                  
// getter
var disabled = $( ".selector" ).widget( "option", "disabled" );
// setter
$( ".selector" ).widget( "option", "disabled", true );

hideType: Boolean or Number or String or Object

Default: null
If and how to animate the hiding of the element.
Multiple types supported:
  • Boolean: When set to false, no animation will be used and the element will be hidden immediately. When set to true, 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, and easing properties may be provided. If the effect 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. If duration or easing is omitted, then the default values will be used. If effect is omitted, then "fadeOut" will be used. If delay is omitted, then no delay is used.
Code examples:

Initialize the widget with the hide option specified:

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

Get or set the hide option, after initialization:

1
2
3
4
5
// getter
var hide = $( ".selector" ).widget( "option", "hide" );
// setter
$( ".selector" ).widget( "option", "hide", { effect: "explode", duration: 1000 } );

showType: Boolean or Number or String or Object

Default: null
If and how to animate the showing of the element.
Multiple types supported:
  • Boolean: When set to false, no animation will be used and the element will be shown immediately. When set to true, 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, and easing properties may be provided. If the effect 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. If duration or easing is omitted, then the default values will be used. If effect is omitted, then "fadeIn" will be used. If delay is omitted, then no delay is used.
Code examples:

Initialize the widget with the show option specified:

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

Get or set the show option, after initialization:

1
2
3
4
5
// getter
var show = $( ".selector" ).widget( "option", "show" );
// setter
$( ".selector" ).widget( "option", "show", { effect: "blind", duration: 800 } );

Methods

_create()

The _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.

_delay( fn [, delay ] )Returns: Number

Invokes the provided function after a specified delay. Keeps this context correct. Essentially setTimeout().

Returns the timeout ID for use with clearTimeout().

  • fn
    Type: Function() or String
    The function to invoke. Can also be the name of a method on the widget.
  • delay
    Type: Number
    The number of milliseconds to wait before invoking the function. Deafults to 0.

_destroy()

The public 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.

_focusable( element )

Sets up element to apply the ui-state-focus class on focus.

The event handlers are automatically cleaned up on destroy.

  • element
    Type: jQuery
    The element(s) to apply the focusable behavior to.

_getCreateEventData()Returns: Object

All widgets trigger the 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.

_getCreateOptions()Returns: Object

This method allows the widget to define a custom method for defining options during instantiation. This user-provided options override the options returned by this method which override the default options.
  • This method does not accept any arguments.

_hide( element, option [, callback ] )

Hides an element immediately, using built-in animation methods, or using custom effects. See the hide option for possible option values.
  • element
    Type: jQuery
    The element(s) to hide.
  • option
    Type: Object
    The settings defining how to hide the element.
  • callback
    Type: Function()
    Callback to invoke after the element has been fully hidden.

_hoverable( element )

Sets up element to apply the ui-state-hover class on hover.

The event handlers are automatically cleaned up on destroy.

  • element
    Type: jQuery
    The element(s) to apply the hoverable behavior to.

_init()

Widgets have the concept of initialization that is distinct from creation. Any time the plugin is called with no arguments or with only an option hash, the widget is initialized; this includes when the widget is created.

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.

_off( element, eventName )

Unbinds event handlers from the specified element(s).
  • element
    Type: jQuery
    The element(s) to unbind the event handlers from. Unlike the _on() method, the elements are required for _off().
  • eventName
    Type: String
    One or more space-separated event types.

_on( [element ], handlers )

Binds event handlers to the specified element(s). Delegation is supported via selectors inside the event names, e.g., "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.
  • Event handlers are automatically namespaced and cleaned up on destroy.
  • element
    Type: jQuery
    Which element(s) to bind the event handlers to. If no element is provided, this.element is used.
  • handlers
    Type: Object
    A map in which the string keys represent the event type and optional selector for delegation, and the values represent a handler function to be called for the event.

_setOption( key, value )

Called from the _setOptions() method for each individual option. Widget state should be updated based on changes.
  • key
    Type: String
    The name of the option to set.
  • value
    Type: Object
    A value to set for the option.

_setOptions( options )

Called whenever the 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.

  • options
    Type: Object
    A map of option-value pairs to set.

_show( element, option [, callback ] )

Shows an element immediately, using built-in animation methods, or using custom effects. See the show option for possible option values.
  • element
    Type: jQuery
    The element(s) to show.
  • option
    Type: Object
    The settings defining how to show the element.
  • callback
    Type: Function()
    Callback to invoke after the element has been fully shown.

_super()

Invokes the method of the same name from the parent widget, with any specified arguments. Essentially .call().
  • This method does not accept any arguments.

_superApply( arguments )

Invokes the method of the same name from the parent widget, with the array of arguments. Essentially .apply().
  • arguments
    Type: Array
    Array of arguments to pass to the parent method.

_trigger( type [, event ] [, data ] )

Triggers an event and its associated callback.

The option with the name equal to type is invoked as the callback.

The event name is the widget name + type.

Note: When providing data, you must provide all three parameters. If there is no event to pass along, just pass null.

  • type
    Type: String
    The type should match the name of a callback option. The full event type will be generated automatically.
  • event
    Type: Event
    The original event that caused this event to occur; useful for providing context to the listener.
  • data
    Type: Object
    A hash of data associated with the event.

destroy()

Removes the widget functionality completely. This will return the element back to its pre-init state.
  • This method does not accept any arguments.

disable()

Disables the widget.
  • This method does not accept any arguments.

enable()

Enables the widget.
  • This method does not accept any arguments.

option( optionName )Returns: Object

Gets the value currently associated with the specified optionName.
  • optionName
    Type: String
    The name of the option to get.
Code examples:

Invoke the method:

1
                                      
var isDisabled = $( ".selector" ).widget( "option", "disabled" );

option()Returns: PlainObject

Gets an object containing key/value pairs representing the current widget options hash.
  • This method does not accept any arguments.
Code examples:

Invoke the method:

1
                                      
var options = $( ".selector" ).widget( "option" );

option( optionName, value )

Sets the value of the widget option associated with the specified optionName.
  • optionName
    Type: String
    The name of the option to set.
  • value
    Type: Object
    A value to set for the option.
Code examples:

Invoke the method:

1
                                      
$( ".selector" ).widget( "option", "disabled", true );

option( options )

Sets one or more options for the widget.
  • options
    Type: Object
    A map of option-value pairs to set.
Code examples:

Invoke the method:

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

widget()Returns: jQuery

Returns a jQuery object containing the original element or other relevant generated element.
  • This method does not accept any arguments.

Events

create( event, ui )Type: widgetcreate

Triggered when the widget is created.
Code examples:

Initialize the widget with the create callback specified:

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

Bind an event listener to the widgetcreate event:

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