Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

jQuery UI Widget Method Calls

jQuery UI Widget Method Calls

Widgets are created with Widget Factory , and methods are used to change their state after initialization and perform actions. There are two ways to call widget methods - through the plugin created by the Widget Factory, or by calling methods on the element's instance object.

Plugin Calls

To call a widget method using the plugin, pass the method name as a string. For example, click here to see how to call the dialog widget's close() Method。



$( ".selector" ).dialog( "close" );

If the method requires arguments, pass them as additional arguments to the plugin. Click here to see how to call the dialog's option() Method。



$( ".selector" ).dialog( "option", "height" );

This returns the dialog's height Option value.

Instance Calls

Each widget instance is stored on the element using jQuery.data() . To retrieve the instance object, call jQuery.data()with the widget's full name as the key, as shown in the example below.



var dialog = $( ".selector" ).data( "ui-dialog" );

Once you have a reference to the instance object, you can call methods on it directly.



var dialog = $( ".selector" ).data( "ui-dialog" );

dialog.close();

In jQuery UI 1.11, the new instance() method makes this process easier.



$( ".selector" ).dialog( "instance" ).close();

Return Type

Most methods called through the widget plugin return a jQuery object, so method calls can be chained with additional jQuery methods. When called on an instance, they return undefinedwith the widget's full name as the key, as shown in the example below.



var dialog = $( ".selector" ).dialog();

 

// Instance invocation - returns undefined

dialog.data( "ui-dialog" ).close();

 

// Plugin invocation - returns a jQuery object

dialog.dialog( "close" );

 

// Therefore, plugin method invocation makes it possible to

// chain method calls with other jQuery functions

dialog.dialog( "close" )

    .css( "color", "red" );

The exceptions are those methods that return information about the widget. For example, the dialog's isOpen() Method。



$( ".selector" )

    .dialog( "isOpen" )

    // This will throw a TypeError

    .css( "color", "red" );

this produces a TypeError error, because isOpen() returns a Boolean value rather than a jQuery object.