Create an Amazon Books Widget with jQuery and XML

It makes sense to forgo database tables and server-side code when you need to store a limited amount of non-sensitive data. Accessing this data can be a snap with jQuery because the library was built to traverse XML documents with ease. With some custom JavaScript and jQuery magic you can create some interesting widgets. A good way to demonstrate this functionality is by building a browsable Amazon.com books widget.

Preface
One thing to remember as you seek to try this out on your own is that Internet Explorer security settings do not allow you to make XmlHttpRequest calls from the local file system. Even though you are not using a server-side language, you still need to run the source code from a Web server like Apache’s HTTP Server. Uploading the files to a Web hosting account would work as well.

This tutorial is using the minified jQuery 1.2.6 core JavaScript file, which can be downloaded here from Google Code. No other plugins are necessary. Here is a screenshot of the widget in its final form:

Step 1: Dissecting the InterfaceI created the following graphic with Illustrator, and this is the framework for the books widget. The final sliced images can be replaced easily to create design elements that suit your needs. The illustration includes the next and previous buttons, as well as the container for the book images. The source ZIP file contains a layered EPS if you would like to make edits without having to start from scratch.

One thing I wanted to do with this widget was to make sure it was flexible enough for just about any column size. That meant that it not only needed to be a fluid width, but it also needed to accept pixel units of measurement. Books can wrap gracefully to multiple rows spaced evenly apart, down to a single column, or can span across in a single row as wide as you like. This next screenshot helps to visualize how that will happen.

The light pink solid blocks are to demonstrate the image slicing grid. There are the two buttons, as well as four corners, the top and bottom background, and then the left and right background. The dark pink solid lines are to demonstrate containment blocks, which will eventually end up as a few divs and an unordered list. To allow for a fluid layout an inner div will contain the left side background, and the unordered list will be nested within this parent div, which will contain the right side background.Step 2: The HTML
Before I get to the HTML, it is worthwhile to note that I am not using PNG files. You could very well substitute PNGs for the GIFs, and it would not affect the functionality. It would mean, however, you would need to implement a fix for the lack of PNG transparency support in Internet Explorer. There are several jQuery plugins that are available.

There is nothing groundbreaking about the HTML, but I would like to point out a few things. The first is with regard to the “overclear” class that appears on several elements. This is an excellent method for clearing floats without the need for additional markup. I discuss this technique in a blog post titled Six indispensable CSS tips and tricks I use on every project. By declaring a width, and setting the overflow property to hidden on a parent div, child elements that are floated will no longer need a trailing element with the clear property.

The second thing I would like to point out is the loader list item. Since I am going to grab all of the books in the XML file at once, the loader should appear immediately. I generated a loader from Ajaxload, and then centered it as a background. When the XML is finished loading, I remove the list item from the DOM, and the loader disappears. Here is a screenshot of what it looks like with just the HTML and CSS applied.

The widget has a fixed width, and for this tutorial it will be a single row with four books displayed at each view. If no width was applied, then it would span the full length of the page, or the width of its parent container.Step 3: The CSS
The CSS is fairly straightforward and self-explanatory, so I will not be spending a great deal of time explaining all the facets of each selector. Almost all selectors are child elements of the parent container with the identifier “books”. You can see that the width applied is optional. Removing it will allow the widget to expand and contract freely.

There is one exception, and that is the informational tool tip applied to a book when you roll over the information icon. Each tool tip contains the class “books_tool_tip”, and are child elements of the page body. These are positioned with JavaScript according to the mouse position at the moment a user moves the cursor onto the icon.

The “books_pointer_left” and “books_pointer_right” classes manage the arrows that are associated with the book details tool tip. The tool tip falls to the right of the cursor, but if it is outside of the viewable browser window (called the viewport), then it will shift to the left side. The classes are swapped, and the arrow shifts to the opposite side as well. This allows you to place the widget in a left column or right column layout.Step 4: The XML
There is nothing revolutionary about this XML. As you will see, each book contains a title, author(s), an image, an Amazon URL, a reviews total, and a reviews average. The XML could be normalized in one area, and that is the “author” node. Strictly speaking, there can be several authors, and an author can be one of two types, an author or an editor. However, I kept it simple in order to focus on the core functionality. A good bit of homework would be to see how you could better optimize that node, and then successfully parse it with jQuery.

Step 5: The JavaScript
The JavaScript is certainly the most complicated portion of the tutorial. As best I can, I usually begin scripts like this by stubbing out the state and behavior of an object to get a feel for functionality. This particular object is simply called “BOOKS”. I also use what is known as the Module Pattern, which is detailed by Eric Miraglia on the Yahoo! User Interface Blog. This design pattern gives you the ability to create private methods and properties. Whenever releasing a script into the wild (like now), this pattern helps to eliminate the possibility of conflicts with other functions and objects other developers may already be using.

var BOOKS = function(){

var _P = {

init : function( params ) {},

params : null,

data : null,

loadXml : function() {},

first : 0,

max : 0,

count : 0,

preloadBooks : function() {},

browseBooks : function( browse ) {},

tooltip : {

show : function( e, $o ) {},

hide : function( e, $o ) {},

getMouseCoord : function( v, e ) {},

getViewport : function() {}

}

};

return {

init : function( params ) {

_P.init( params );

}

};

}();

All of my private members I placed inside of an object called “_P”. This has more to do with organizational efforts than anything. So long as a member is not in the BOOKS return statement, I could very well have created it as a standalone variable or function. Since I need a way to associate public parameters (settings) with private members, I have one public method. This public initialization method will pass the settings along to a private initialization method, acting as a go-between. I will revisit those settings in the final step.

I will not cover every piece of functionality, but I did want to highlight a few very important aspects of the script — the first being the “loadXml” method. This is one of jQuery’s AJAX utilities, and one of the easiest AJAX implementations to use. You can read more about it in the official documentation. After retrieving an XML file, many developers will perform actions on the data all within the success portion of the call. This is difficult to troubleshoot, and I prefer to pass that data outside to other methods to act upon it. This is thinking in object-oriented terms, and it can be a good habit.

The “preloadBooks” method is what parses the XML data, and turns each node into relevant XHTML, including both a book and a book’s tool tip. The great thing about jQuery is that XML nodes can be treated just like HTML nodes. You do not have to learn two styles of syntax, with the only caveat being that you have to use jQuery’s text() method to grab content between a start and end tag. With HTML, you would use the html() method.

There is a large portion of the HTML that needs to be built through JavaScript. This often involves string concatenation. The traditional approach is to use the addition arithmetic operator, but a faster approach is to place portions of a string inside an array, and then join them. I do this in several places, and especially when it happens continuously throughout a loop, then this is the preferred style.

Now that the books HTML has all been inserted into the DOM, it is time to attach the appropriate events for browsing. The action of browsing happens in the “browseBooks” method. This method accepts the “browse” parameter, which takes one of two arguments, “prev” or “next”. This is not a scrolling action, but a fade in/fade out transition. The method will establish the first (current) position, the maximum number of books to browse, the number of books left to browse, and then it will perform the transition. This also helps to determine when the previous or next buttons should be displayed in order to restrict users from browsing beyond the number of books listed.

The tool tip involves a small amount of custom JavaScript, and I wanted to describe two functions — the “getMouseCoord” and “getViewport” methods. These are cross-browser implementations for determining the mouse position in accordance with how far the page has scrolled up/down or left/right. You should never have to edit these, and I have successfully used them on several projects without any issue. The “show” method also handles the scenario I described earlier, when the tool tip falls outside of the calculated viewport.Step 6: The Final Widget

The last thing to do is to pass the settings through to the JavaScript initialization method from the HTML. There are three arguments: the path to the XML file, the path to the images used in the JavaScript, and the number of books you would like displayed per view. For this tutorial, it is assumed there is only one books widget per page (called “books”), which is why there is no parameter for ID or class name. Here is the XHTML in final form: