HOWTO: build a Technorati top tags ticker with PHP, jQuery, JavaScript and AJAX - day 3 of 3
The third and final installment of this three day tutorial has arrived, and the completed ticker is finally unveiled. On day one I reviewed the Technorati API and the PHP, and on day two I walked through the XHTML and CSS. Today, I will break down the jQuery, JavaScript and AJAX components of the ticker. For those of you unwilling to wait for the reveal, click here for a demo.
Please note that the demo contains a reference to a static XML file, while the ZIP contains a reference to a PHP page per the discussion on day one.
Day 3: An introduction to the jQuery, JavaScript and AJAX
There is quite a bit to digest in the following code. I thought it would be best to give an overview of the business logic itself, instead of a drilling down line-by-line. Conceptually, it will be easy to understand, but you might feel lost without experience in jQuery or JavaScript object literal notation. I want to highlight the key aspects of the code, but I suggest you keep Visual jQuery handy for reference. For more information on object literal notation, I suggest a Google search.
$(function() {
var ticker = {
ul_width: 0,
init: function() {
ticker.timer = window.setInterval(ticker.animate,250);
},
animate: function() {
$("ul","#ticker").css("left",(parseInt( $("ul","#ticker").css("left")) - 5) + "px");
},
timer: null,
close: function() {
$("#ticker").slideUp("normal",function() {
window.clearInterval(ticker.timer);
});
}
};
$(".png").each(function() {
var src = "images/" + $(this).attr("id") + ".png";
if ($.browser.msie) {
$(this).css("filter", "progid:DXImageTransform. Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')");
} else {
$(this).attr("src",src);
}
});
$.ajax({
type: "GET",
url: "toptags.xml",
dataType: "xml",
success: function(data) {
$(".inner","#ticker").append("<ul></ul>");
$("/tapi/document/item/tag", data).each(function(){
var t = $(this).text().toLowerCase();
$("ul","#ticker").append("<li><a href='http://www.technorati.com/tag/" + t + "'>" + t + "</a></li>");
});
$("li","#ticker").each(function() {
ticker.ul_width += $(this).width() + 20;
$(this).css("margin-right","20px");
}).parent().css("width",ticker.ul_width + "em").css("left", Math.round(parseInt($(".inner", "#ticker").css("width"))/2) + "px");
ticker.init();
$("#ticker").mouseover(function() {
window.clearInterval(ticker.timer);
});
$("#ticker").mouseout(function() {
ticker.init();
});
$(".close","#ticker").click(function() {
ticker.close();
return false;
});
}
});
});
The ticker object manages the process for animating, stopping, and closing the ticker. The ul_width property is used to hold a reference to the total width of the unordered list of top tags. If you need to adjust the speed at which the ticker animates, then I would suggest changing the milliseconds value on the init method. As a rule of thumb I never go lower than 10 — the lower the number, the more memory it requires from the browser. At a certain threshold it can cause other widgets on the page to perform poorly.
The png class loop helps give cross-browser PNG transparency to the two PNG files in the ticker (essentially for IE6). A simple trick is to give those images an image source that references a transparent GIF. When the page loads, I use the id attribute to give me the name of the real image, and then I can apply the AlphaImageLoader filter, or replace the source. Remember, for this to work the image has to have a width and height specified.
The AJAX is where jQuery really shines. There are several techniques in the framework for achieving the desired results. I have chosen this one for the tutorial because it is the most obvious. I make a GET request for the PHP page that is going to respond with an XML file (dataType), which if received successfully, I will use to populate the ticker. There are a few other methods and properties, including a method for managing a failed (or no) response that can be very useful.
Inside the success method is where the magic happens. I append an unordered list to the ticker, and then iterate through each tag node. The jQuery selector is using XPath, a query language built specifically for searching data in an XML document. I grab the text in the nodes, and I build a list item and URL that jumps off to Technorati’s Web site.
For each of the list items, I want to grab the width, add another 20 pixels for the margin, and then add it to the ul_width property. This will tell me what size the unordered list should be in order to contain all the list items floated on a single line. I could give the ul an arbitrary width, but I want to be sure to prevent wrapping. If the text wraps, the ticker will break.
There is one important point to make regarding the width of the ul. You will notice I calculated pixels, but I applied the width using the em measurement. If a user resizes the text, it is important that the ticker flex to accommodate. Since em is a relative measurement, it will grow accordingly. In essence, this does not provide us with an exact measurement, because there is no one-to-one relationship between px and em. However, it will always allow enough space for the list items.
The ticker is finally positioned to the left one-half of the width of the inner div. The Technorati ticker begins movement at the left-most position, which prevents users from seeing all the tags immediately, so this aspect has been changed. The animation is then initialized, and lastly, the three event listeners needed to stop, (re)start, and close the ticker are attached. Just like the Technorati ticker, the animation runs indefinitely. There was probably little need to stop it since it only appears on the home page, which is not meant to act as a true destination, but a summary of deeper site content. I suggest you take the same approach if you do implement the ticker.
I hope you have enjoyed this series of tutorials. Feel free to comment here, or email me with any comments or questions. Click here to download all the files in a ZIP archive.
Leave a Comment
Comments are moderated. No profanity. Only <a>...</a>, <blockquote>...</blockquote>, and <code>...</code> are allowed.
Seperate paragraphs by pressing the "Enter" key twice, or press it once to break to a new line.
1 Comment
#01, Nov 12 2007
An introduction to the jQuery, JavaScript and AJAX « Open source for developer
[…] An introduction to the jQuery, JavaScript and AJAX ที่มา:http://blog.reindel.com/2007/08/23/howto-build-a-technorati-top-tags-ticker-with-php-jquery-javascript-and-ajax-day-3-of-3/ […]