Sunday, August 26, 2012

Tinkering with jQuery UI Widgets Part 1: Making Multiple Widgets Work Together

After spending some time digging into the features of the jQuery UI library. I'm really impressed with how its been constructed. The base class is a great factory for creating new widgets which are just jQuery plugins with some default structure to guide you in the "best practices" direction to building stateful, highly functional widgets. Additionally, the library has been decomposed into widgets that provide very specific behaviors that can be easily combined to create more complex functionality. This is made possible by the fact that you can chain widget calls together just like any other jQuery method/plugins and add the behaviors you need to your target element.

As an example, say I have a box on my page that I want to drag around and make resizable. Out-of-the-box, jQuery UI provides two widgets to enable this behavior - Draggable and Resizable. You can easily combined these two widgets on your box element to enable both behaviors:


Pretty easy, right? Now you can add more functionality - even responding to critical events defined by each widget:

maxHeight: 500,
maxWidth: 500,
minHeight: 100,
minWidth: 100
grid: [50, 50],
stop: function (e, ui)
alert('done dragging!');

As you can see, just by combining some of the built-in UI widgets, you can build some pretty sophisticated logic just by combining two (or more) widgets together.

In part 2, we'll explore how to encapsulate this new behavior into a custom widget: ColorBox.