1. Code
  2. Coding Fundamentals
  3. XML

Create an Amazon Books Widget with jQuery and XML

Scroll to top

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 Interface

I 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.

1
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
4
<head>
5
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
6
<title>Amazon.com Books Widget</title>
7
<link rel="stylesheet" href="css/books.css" type="text/css" media="screen" />
8
</head>
9
<body>
10
11
12
	<div id="books">
13
		<div class="overclear buttons">
14
			<a href="#" class="prev"><img src="images/books_prev.gif" width="40" height="30" alt="Previous" /></a>
15
			<div class="showing"><!-- showing --></div>
16
			<a href="#" class="next"><img src="images/books_next.gif" width="40" height="30" alt="Next" /></a>
17
		</div>
18
		<div class="overclear top">
19
			<img src="images/books_left_top.gif" width="20" height="20" alt="" class="float_left" />
20
			<img src="images/books_right_top.gif" width="20" height="20" alt="" class="float_right" />
21
		</div>
22
		<div class="inner">
23
			<ul class="overclear">
24
				<li class="loader"><!-- loader --></li>
25
			</ul>
26
		</div>
27
		<div class="overclear btm">
28
			<img src="images/books_left_btm.gif" width="20" height="20" alt="" class="float_left" />
29
			<img src="images/books_right_btm.gif" width="20" height="20" alt="" class="float_right" />
30
		</div>
31
	</div>
32
33
</body>
34
</html>

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.

1
2
/* foundation */
3
4
body {
5
	font: 100% normal "Arial", "Helvetica", sans-serif;
6
}
7
#books {
8
	width: 515px; /* optional */
9
}
10
#books img {
11
	border: 0;
12
}
13
#books .clear_both {
14
	clear: both;
15
}
16
#books .float_left,
17
#books  ul li {
18
	float: left;
19
	display: inline;
20
}
21
#books .float_right {
22
	float: right;
23
}
24
#books .overclear {
25
	width: 100%;
26
	overflow: hidden;
27
}
28
29
/* styles */
30
31
#books .buttons {
32
	position: relative;
33
	height: 30px;
34
	margin: 0 0 5px 0;
35
}
36
#books .prev {
37
	position: absolute;
38
	top: 0;
39
	left: 0;
40
	visibility: hidden;
41
}
42
#books .next {
43
	position: absolute;
44
	top: 0;
45
	right: 0;
46
}
47
#books .showing {
48
	margin: 5px 60px 0 60px;
49
	text-align: center;
50
	font-size: .8em;
51
}
52
#books .top {
53
	background: url(../images/books_top.gif) repeat-x;
54
}
55
#books .inner {
56
	padding: 0 0 0 20px;
57
	margin: 0 0 -20px 0;
58
	background: url(../images/books_left_mid.gif) repeat-y;
59
}
60
#books  ul {
61
	margin: 0;
62
	padding: 0;
63
	list-style-type: none;
64
	background: url(../images/books_right_mid.gif) repeat-y top right;
65
}
66
#books  ul li {
67
	display: none;
68
	position: relative;
69
	margin: 0;
70
	padding: 0 20px 20px 0;
71
	font-size: .8em;
72
	z-index: 1;
73
}
74
#books  ul li.loader {
75
	display: block;
76
	float: none;
77
	height: 115px;
78
	margin: 0 0 20px -20px;
79
	background: url(../images/books_loader.gif) no-repeat center center;
80
}
81
#books  ul li a.info {
82
	position: absolute;
83
	bottom: 20px;
84
	right: 20px;
85
}
86
#books  ul li a.thumb {
87
	display: block;
88
	border: 1px solid #ddd;
89
}
90
#books  ul li a.thumb img {
91
	display: block;
92
	margin: 0;
93
	padding: 3px;
94
}
95
#books .btm {
96
	background: url(../images/books_btm.gif) repeat-x;
97
}
98
.books_tool_tip {
99
	display: none;
100
	position: absolute;
101
	top: 0;
102
	left: 0;
103
	width: 350px;
104
	z-index: 9999;
105
}
106
.books_tool_tip .books_pointer_left {
107
	position: absolute;
108
	top: 0;
109
	left: 0;
110
	width: 10px;
111
	height: 10px;
112
	background: url(../images/books_pointer_left.gif);
113
}
114
.books_tool_tip .books_pointer_right {
115
	position: absolute;
116
	top: 0;
117
	right: 0;
118
	width: 10px;
119
	height: 10px;
120
	background: url(../images/books_pointer_right.gif);
121
}
122
.books_tool_tip .inner {
123
	border: 1px solid #ddd;
124
	padding: 15px 15px 3px 15px;
125
	margin: 0 0 0 9px;
126
	background: #fff;
127
}
128
.books_tool_tip .inner_right {
129
	margin: 0 9px 0 0;
130
}
131
.books_tool_tip .inner p {
132
	font-size: .8em;
133
	margin: 0;
134
	padding: 0 0 12px 0;
135
}

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.

1
2
<?xml version="1.0" encoding="UTF-8"?>
3
<books>
4
	<book>
5
		<title><![CDATA[Design Patterns: Elements of Reusable Object-Oriented Software]]></title>
6
		<author>Erich Gamma, Richard Helm, Ralph Johnson, John M. Vlissides</author>
7
		<image width="95" height="115">
8
			<src><![CDATA[images/books/isbn_0201633612.jpg]]></src>
9
		</image>
10
		<href><![CDATA[http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612/]]></href>
11
		<reviews>
12
			<total>250</total>
13
			<average_rating>4.5</average_rating>
14
		</reviews>
15
	</book>
16
	<book>
17
		<title><![CDATA[The Pragmatic Programmer: From Journeyman to Master]]></title>
18
		<author>Andrew Hunt, David Thomas</author>
19
		<image width="95" height="115">
20
			<src><![CDATA[images/books/isbn_020161622X.jpg]]></src>
21
		</image>
22
		<href><![CDATA[http://www.amazon.com/Pragmatic-Programmer-Journeyman-Master/dp/020161622X/]]></href>
23
		<reviews>
24
			<total>131</total>
25
			<average_rating>4.5</average_rating>
26
		</reviews>
27
	</book>
28
	<book>
29
		<title><![CDATA[Refactoring: Improving the Design of Existing Code]]></title>
30
		<author>Martin Fowler, Kent Beck, John Brant, William Opdyke</author>
31
		<image width="95" height="115">
32
			<src><![CDATA[images/books/isbn_0201485672.jpg]]></src>
33
		</image>
34
		<href><![CDATA[http://www.amazon.com/Refactoring-Improving-Existing-Addison-Wesley-Technology/dp/0201485672/]]></href>
35
		<reviews>
36
			<total>139</total>
37
			<average_rating>4.5</average_rating>
38
		</reviews>
39
	</book>
40
	<book>
41
		<title><![CDATA[Patterns of Enterprise Application Architecture]]></title>
42
		<author>Martin Fowler</author>
43
		<image width="95" height="115">
44
			<src><![CDATA[images/books/isbn_0321127420.jpg]]></src>
45
		</image>
46
		<href><![CDATA[http://www.amazon.com/Enterprise-Application-Architecture-Addison-Wesley-Signature/dp/0321127420/]]></href>
47
		<reviews>
48
			<total>56</total>
49
			<average_rating>4.5</average_rating>
50
		</reviews>
51
	</book>
52
	<book>
53
		<title><![CDATA[Head First Design Patterns]]></title>
54
		<author>Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra</author>
55
		<image width="95" height="115">
56
			<src><![CDATA[images/books/isbn_0596007124.jpg]]></src>
57
		</image>
58
		<href><![CDATA[http://www.amazon.com/Head-First-Design-Patterns/dp/0596007124/]]></href>
59
		<reviews>
60
			<total>252</total>
61
			<average_rating>4.5</average_rating>
62
		</reviews>
63
	</book>
64
	<book>
65
		<title><![CDATA[Introduction to Algorithms]]></title>
66
		<author>Thomas Cormen, Charles Leiserson, Ronald Rivest, Clifford Stein</author>
67
		<image width="95" height="115">
68
			<src><![CDATA[images/books/isbn_0262032937.jpg]]></src>
69
		</image>
70
		<href><![CDATA[http://www.amazon.com/Introduction-Algorithms-Thomas-Cormen/dp/0072970545/]]></href>
71
		<reviews>
72
			<total>167</total>
73
			<average_rating>4.0</average_rating>
74
		</reviews>
75
	</book>
76
	<book>
77
		<title><![CDATA[The Mythical Man-Month: Essays on Software Engineering, Anniversary Edition (2nd Edition)]]></title>
78
		<author>Frederick P. Brooks</author>
79
		<image width="95" height="115">
80
			<src><![CDATA[images/books/isbn_0201835959.jpg]]></src>
81
		</image>
82
		<href><![CDATA[http://www.amazon.com/Mythical-Man-Month-Software-Engineering-Anniversary/dp/0201835959/]]></href>
83
		<reviews>
84
			<total>128</total>
85
			<average_rating>4.5</average_rating>
86
		</reviews>
87
	</book>
88
	<book>
89
		<title><![CDATA[Effective Java (2nd Edition)]]></title>
90
		<author>Joshua Bloch</author>
91
		<image width="95" height="115">
92
			<src><![CDATA[images/books/isbn_0321356683.jpg]]></src>
93
		</image>
94
		<href><![CDATA[http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683/]]></href>
95
		<reviews>
96
			<total>120</total>
97
			<average_rating>5.0</average_rating>
98
		</reviews>
99
	</book>
100
	<book>
101
		<title><![CDATA[Mastering Regular Expressions]]></title>
102
		<author>Jeffrey Friedl</author>
103
		<image width="95" height="115">
104
			<src><![CDATA[images/books/isbn_0596528124.jpg]]></src>
105
		</image>
106
		<href><![CDATA[http://www.amazon.com/Mastering-Regular-Expressions-Jeffrey-Friedl/dp/0596528124/]]></href>
107
		<reviews>
108
			<total>125</total>
109
			<average_rating>4.5</average_rating>
110
		</reviews>
111
	</book>
112
	<book>
113
		<title><![CDATA[Introduction to the Theory of Computation, Second Edition]]></title>
114
		<author>Michael Sipser</author>
115
		<image width="95" height="115">
116
			<src><![CDATA[images/books/isbn_0534950973.jpg]]></src>
117
		</image>
118
		<href><![CDATA[http://www.amazon.com/Introduction-Theory-Computation-Second-Michael/dp/0534950973/]]></href>
119
		<reviews>
120
			<total>52</total>
121
			<average_rating>4.5</average_rating>
122
		</reviews>
123
	</book>
124
	<book>
125
		<title><![CDATA[Don't Make Me Think: A Common Sense Approach to Web Usability (2nd Edition)]]></title>
126
		<author>Steve Krug</author>
127
		<image width="95" height="115">
128
			<src><![CDATA[images/books/isbn_0321344758.jpg]]></src>
129
		</image>
130
		<href><![CDATA[http://www.amazon.com/Dont-Make-Me-Think-Usability/dp/0321344758/]]></href>
131
		<reviews>
132
			<total>453</total>
133
			<average_rating>4.5</average_rating>
134
		</reviews>
135
	</book>
136
	<book>
137
		<title><![CDATA[The Visual Display of Quantitative Information, 2nd edition]]></title>
138
		<author>Edward R. Tufte</author>
139
		<image width="95" height="115">
140
			<src><![CDATA[images/books/isbn_0961392142.jpg]]></src>
141
		</image>
142
		<href><![CDATA[http://www.amazon.com/Visual-Display-Quantitative-Information-2nd/dp/0961392142/]]></href>
143
		<reviews>
144
			<total>96</total>
145
			<average_rating>4.5</average_rating>
146
		</reviews>
147
	</book>
148
	<book>
149
		<title><![CDATA[JavaScript: The Definitive Guide]]></title>
150
		<author>David Flanagan</author>
151
		<image width="95" height="115">
152
			<src><![CDATA[images/books/isbn_0596101996.jpg]]></src>
153
		</image>
154
		<href><![CDATA[http://www.amazon.com/JavaScript-Definitive-Guide-David-Flanagan/dp/0596101996/]]></href>
155
		<reviews>
156
			<total>278</total>
157
			<average_rating>4.5</average_rating>
158
		</reviews>
159
	</book>
160
	<book>
161
		<title><![CDATA[Designing Interfaces: Patterns for Effective Interaction Design]]></title>
162
		<author>Jenifer Tidwell</author>
163
		<image width="95" height="115">
164
			<src><![CDATA[images/books/isbn_0596008031.jpg]]></src>
165
		</image>
166
		<href><![CDATA[http://www.amazon.com/Designing-Interfaces-Patterns-Effective-Interaction/dp/0596008031/]]></href>
167
		<reviews>
168
			<total>47</total>
169
			<average_rating>4.5</average_rating>
170
		</reviews>
171
	</book>
172
	<book>
173
		<title><![CDATA[Universal Principles of Design]]></title>
174
		<author>William Lidwell, Kritina Holden, Jill Butler</author>
175
		<image width="95" height="115">
176
			<src><![CDATA[images/books/isbn_1592530079.jpg]]></src>
177
		</image>
178
		<href><![CDATA[http://www.amazon.com/Universal-Principles-Design-William-Lidwell/dp/1592530079/]]></href>
179
		<reviews>
180
			<total>54</total>
181
			<average_rating>4.5</average_rating>
182
		</reviews>
183
	</book>
184
	<book>
185
		<title><![CDATA[Ambient Findability: What We Find Changes Who We Become]]></title>
186
		<author>Peter Morville</author>
187
		<image width="95" height="115">
188
			<src><![CDATA[images/books/isbn_0596007655.jpg]]></src>
189
		</image>
190
		<href><![CDATA[http://www.amazon.com/Ambient-Findability-What-Changes-Become/dp/0596007655/]]></href>
191
		<reviews>
192
			<total>46</total>
193
			<average_rating>4.0</average_rating>
194
		</reviews>
195
	</book>
196
	<book>
197
		<title><![CDATA[The Search: How Google and Its Rivals Rewrote the Rules of Business and Transformed Our Culture]]></title>
198
		<author>John Battelle</author>
199
		<image width="95" height="115">
200
			<src><![CDATA[images/books/isbn_1591841410.jpg]]></src>
201
		</image>
202
		<href><![CDATA[http://www.amazon.com/Search-Rewrote-Business-Transformed-Culture/dp/B000QRIHXE/]]></href>
203
		<reviews>
204
			<total>99</total>
205
			<average_rating>4.5</average_rating>
206
		</reviews>
207
	</book>
208
	<book>
209
		<title><![CDATA[Beginning PHP and MySQL 5 (2nd Edition)]]></title>
210
		<author>W. Jason Gilmore</author>
211
		<image width="95" height="115">
212
			<src><![CDATA[images/books/isbn_1590595521.jpg]]></src>
213
		</image>
214
		<href><![CDATA[http://www.amazon.com/Beginning-PHP-MySQL-Novice-Professional/dp/1590595521/]]></href>
215
		<reviews>
216
			<total>100</total>
217
			<average_rating>4.0</average_rating>
218
		</reviews>
219
	</book>
220
</books>

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.

1
2
var BOOKS = function(){
3
	var _P = {
4
		init : function( params ) {},
5
		params : null,
6
		data : null,
7
		loadXml : function() {},
8
		first : 0,
9
		max : 0,
10
		count : 0,
11
		preloadBooks : function() {},
12
		browseBooks : function( browse ) {},
13
		tooltip : {
14
			show : function( e, $o ) {},
15
			hide : function( e, $o ) {},
16
			getMouseCoord : function( v, e ) {},
17
			getViewport : function() {}
18
		}
19
	};
20
	return {
21
		init : function( params ) {
22
			_P.init( params );
23
		}
24
	};
25
}();

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.

Here is a look now at the final JavaScript:

1
2
var BOOKS = function(){
3
	var _P = {
4
		init : function( params ) {
5
			_P.params = params;
6
			_P.loadXml();
7
		},
8
		params : null,
9
		data : null,
10
		loadXml : function() {
11
			$.ajax({
12
				type : "GET",
13
				url : _P.params.xmlPath,
14
				dataType : "xml",
15
				success : function( data ) {
16
					_P.data = data;
17
					_P.max = _P.params.perView;
18
					_P.count = $( "book", data ).length;
19
					_P.preloadBooks();
20
					_P.browseBooks();
21
				}
22
			});
23
		},
24
		first : 0,
25
		max : 0,
26
		count : 0,
27
		preloadBooks : function() {
28
			$( "ul", "#books" ).empty();
29
			$( "book", _P.data ).each(function( i ) {
30
				var title = $.trim( $( "title", this ).text() );
31
				var href = $.trim( $( "href", this ).text() );
32
				$( "ul", "#books" ).append([
33
					"<li><a href='",
34
					href,
35
					"' class='info'><img src='",
36
					_P.params.imgPath,
37
					"/books_info.gif' width='15' height='16' alt='More Info' /></a><a href='",
38
					href,
39
					"' class='thumb'><img src='",
40
					$.trim( $( "image > src", this ).text() ),
41
					"' width='",
42
					$( "image", this ).attr( "width" ),
43
					"' height='",
44
					$( "image", this ).attr( "height" ),
45
					"' alt='",
46
					title,
47
					"' /></a></li>" ].join( "" ));
48
				$( "body" ).append([
49
					"<div class='books_tool_tip' id='books_tool_tip_",
50
					i,
51
					"'><div class='books_pointer_left'><!-- books pointer --></div><div class='inner'><p>",
52
					title,
53
					" (by <em>",
54
					$.trim( $( "author", this ).text() ),
55
					"</em>)",
56
					"</p><p><img src='",
57
					_P.params.imgPath,
58
					"/stars_",
59
					$.trim( $( "reviews > average_rating", this ).text() ),
60
					,".gif' width='55' height='12' /> (",
61
					$.trim( $( "reviews > total", this ).text() ),
62
					")",
63
					"</p></div></div>" ].join( "" ));
64
			});
65
			$( ".info", "#books" ).hover(function( e ) {
66
				_P.tooltip.show( e, $( "#books_tool_tip_" + $( "a.info", "#books" ).index( this ) ) );
67
			}, function( e ) {
68
				_P.tooltip.hide( e, $( "#books_tool_tip_" + $( "a.info", "#books" ).index( this ) ) );
69
			});
70
			$( "#books .prev" ).click(function() {
71
				_P.browseBooks( "prev" );
72
				return false;
73
			});
74
			$( "#books .next" ).click(function() {
75
				_P.browseBooks( "next" );
76
				return false;
77
			});
78
		},
79
		browseBooks : function( browse ) {
80
			if ( browse == "prev" ) {
81
				if ( _P.first == _P.count && ( _P.count % _P.max > 0 ) ) {
82
					_P.first = _P.first - ( ( _P.count % _P.max ) + _P.max );
83
				} else {
84
					_P.first = _P.first - ( _P.max * 2 );
85
				}
86
			}
87
			var range = _P.first + _P.max;
88
			var start = 1;
89
			if ( range > _P.max ) {
90
				start = ( ( range - _P.max ) + 1 );
91
			}
92
			if ( _P.first == 0 ) {
93
				$( "#books .prev" ).css( "visibility", "hidden" );
94
			} else {
95
				$( "#books .prev" ).css( "visibility", "visible" );
96
			}
97
			if ( range < _P.count ) {
98
				$( "#books .next" ).css( "visibility", "visible" );
99
			} else if ( range >= _P.count ) {
100
				range = _P.count;
101
				$( "#books .next" ).css( "visibility", "hidden" );
102
			}
103
			$( "book", _P.data ).each(function( i ) {
104
				if ( i >= _P.first && i < range ) {
105
					$( "#books li:eq(" + i + ")" ).fadeIn( "slow" );
106
				} else {
107
					$( "#books li:eq(" + i + ")" ).css( "display", "none" );
108
				}
109
			});
110
			_P.first = range;
111
			$( "#books .showing" ).html([
112
				"Viewing <strong>",
113
				start,
114
				" - ",
115
				range,
116
				"</strong> of <strong>",
117
				_P.count,
118
				"</strong>" ].join( "" ));
119
		},
120
		tooltip : {
121
			show : function( e, $o ) {
122
				var v = _P.tooltip.getViewport();
123
				var pageX = _P.tooltip.getMouseCoord( v, e )[0] + 15;
124
				var pageY = _P.tooltip.getMouseCoord( v, e )[1];
125
				$o.find( ".books_pointer_right" ).addClass( "books_pointer_left" ).removeClass( "books_pointer_right" );
126
				if ( pageX + $o.width() > v.innerWidth + v.pageXOffset ) {
127
					pageX = pageX - $o.width() - 30;
128
					$o.find( ".inner" ).addClass( "inner_right" );
129
					$o.find( ".books_pointer_left" ).addClass( "books_pointer_right" ).removeClass( "books_pointer_left" );
130
				}
131
				$o.css( "left", pageX ).css( "top", pageY ).css( "display", "block" );
132
			},
133
			hide : function( e, $o ) {
134
				$o.css( "display", "none" );
135
			},
136
			getMouseCoord : function( v, e ) {
137
				( !e ) ? e = window.event : e = e;
138
				( e.pageX ) ? v.pageX = e.pageX : v.pageX = e.clientX + v.scrollLeft;
139
				( e.pageY ) ? v.pageY = e.pageY : v.pageY = e.clientY + v.scrollTop;
140
				return [ e.pageX, e.pageY ];
141
			},
142
			getViewport : function() {
143
				var viewport = {}
144
				if ( self.innerHeight ) {
145
					viewport.pageYOffset = self.pageYOffset;
146
					viewport.pageXOffset = self.pageXOffset;
147
					viewport.innerHeight = self.innerHeight;
148
					viewport.innerWidth = self.innerWidth;
149
				} else if ( document.documentElement && document.documentElement.clientHeight ) {
150
					viewport.pageYOffset = document.documentElement.scrollTop;
151
					viewport.pageXOffset = document.documentElement.scrollLeft;
152
					viewport.innerHeight = document.documentElement.clientHeight;
153
					viewport.innerWidth = document.documentElement.clientWidth;
154
				}
155
				return viewport;
156
			}
157
		}
158
	};
159
	return {
160
		init : function( params ) {
161
			_P.init( params );
162
		}
163
	};
164
}();

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

Final ProductFinal ProductFinal Product

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:

1
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
4
<head>
5
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
6
<title>Amazon.com Books Widget</title>
7
<link rel="stylesheet" href="css/books.css" type="text/css" media="screen" />
8
<script language="javascript" type="text/javascript" src="js/jquery-1.2.6.min.js"></script>
9
<script language="javascript" type="text/javascript" src="js/books.js"></script>
10
<script language="javascript" type="text/javascript">
11
12
	$(function(){
13
		BOOKS.init({
14
			xmlPath : "data/books.xml",
15
			imgPath : "images",
16
			perView : 4
17
		});
18
	});
19
20
</script>
21
</head>
22
<body>
23
24
	<div id="books">
25
		<div class="overclear buttons">
26
			<a href="#" class="prev"><img src="images/books_prev.gif" width="40" height="30" alt="Previous" /></a>
27
			<div class="showing"><!-- showing --></div>
28
			<a href="#" class="next"><img src="images/books_next.gif" width="40" height="30" alt="Next" /></a>
29
		</div>
30
		<div class="overclear top">
31
			<img src="images/books_left_top.gif" width="20" height="20" alt="" class="float_left" />
32
			<img src="images/books_right_top.gif" width="20" height="20" alt="" class="float_right" />
33
		</div>
34
		<div class="inner">
35
			<ul class="overclear">
36
				<li class="loader"><!-- loader --></li>
37
			</ul>
38
		</div>
39
		<div class="overclear btm">
40
			<img src="images/books_left_btm.gif" width="20" height="20" alt="" class="float_left" />
41
			<img src="images/books_right_btm.gif" width="20" height="20" alt="" class="float_right" />
42
		</div>
43
	</div>
44
45
</body>
46
</html>
jQuery Amazon Book ListjQuery Amazon Book ListjQuery Amazon Book List

Enjoy your Amazon.com books widget!

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.