Writing jQuery Widgets ( 1.7+ )

It is easy to create your own jQuery widgets. First make sure you include the jQuery and jQuery.ui libraries.

The next step is to define our widget using the $.widget helper method.


$.widget("ui.name", {
    _init: function() {
    },
    _privateMethod: function() {
    },
    method: function(arg1, arg2) {
    }
});

The _init function is the constructor of the widget. Methods that start with “_” are private and cannot be accessed. All other methods are public and accessible outside the object by calling:


    $("id").name("method_name", par1, par2); 

If the method returns a value you need to add it to the object “getter” declaration (See below).

To access the element used to build the widget inside the object use:


    this.element

To access the options passed to the widget use:


    this.options

To set default properties:


    $.extend($.ui.name, {
        defaults: {
           option: value
        }
    });

To define “getter” methods:


    $.extend($.ui.name, {
        getter: [ "method", "method2" ]
    });

Leave a Reply

You must be logged in to post a comment.