One of the topics that was of great interest at #jqcon was jQueryUI and it’s impressive widget library. What didn’t receive as much attention was how exactly to go about creating widgets that are compatible with jQueryUI. In this first of a series of articles in jQueryUI development, we’ll cover the basics of creating a simple jQueryUI widget. In future articles, we’ll look at how to pair widgets together using the Publisher / Subscriber (pub/sub) pattern.
This carousel is probably not quite robust enough to be deployed to production and I urge you to avoid copying and pasting this code into your live site. This basic carousel aims to teach you how to build one yourself as well as how to build a jQueryUI widget.
Create the Basic HTML Markup
To begin, we need a basic page and some photos thumbnails to work with. The thumbnails, as you’ll see later, can be any size you choose and our carousel will expand to fit them. Note especially that we’re only including some basic shell markup. There are a few good reasons for this decision: First, it keeps our basic document clean and free of extraneous markup. Second, it is far less work for people implementing our widget—and fewer potential points of error in their process.
<div id="slide">
<div>
<img src="img/carousel/0_10.jpg" width="78" height="29" alt="" />
</div>
<div>
<img src="img/carousel/0_11.jpg" width="78" height="58" alt="" />
</div>
<div>
<img src="img/carousel/1_6.jpg" width="78" height="58" alt="" />
</div>
<div>
<img src="img/carousel/1_4.jpg" width="78" height="58" alt="" />
</div>
<div>
<img src="img/carousel/0_9.jpg" width="78" height="58" alt="" />
</div>
</div>
For demonstration purposes, I’ve chosen the Cupertino theme available for download from the jQueryUI ThemeRoller application. You can choose any theme you desire—or create your own. Also, you can see I’ve created a reference to a carousel.js file. We’ll create this file as we continue.
Create the basic framework of a jQueryUI plugin
Now that we have our basic structure in place for the carousel, we can begin to create the javascript that will control the animation and interaction. jQueryUI provides a great construct called $.widget() that will encapsulate all of the functionality of the widget within a single namespace and construct. Let’s start by creating a basic widget: