Alternate colors to table rows with javascript (YUI)

This article will show you how to add alternate colors to table rows without any server side development or hard coding your scripts, thus providing good readability for your users and great flexibility for you. We will use the YUI library for that.

The HTML

We need to create our basic HTML file containing a table and adding a class name to it.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Alternate colors</title>
	</head>
	<body>
		<table class="alternateRows">
			<tr>
				<td>First Row</td>
			</tr>
			<tr>
				<td>Second Row</td>
			</tr>
			<tr>
				<td>Third Row</td>
			</tr>
			<tr>
				<td>Fourth Row</td>
			</tr>
			<tr>
				<td>Fifth Row</td>
			</tr>
		</table>
	</body>
</html>

The Javascript

Next we need to include the YUI libraries, served from their CDN. We need the

  • YAHOO global object which contains a number of methods that are used throughout the library
  • DOM collection which provides methods that simplify common DOM-scripting tasks, including element positioning and CSS style management
  • Event utility for various event handling
<!-- Combo-handled YUI JS files: --> 
<script type="text/javascript" src="http://yui.yahooapis.com/combo?2.6.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>

And also our javascript file, alternate.js

<script type="text/javascript" src="alternate.js"></script>

So our HTML page looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<!-- Combo-handled YUI JS files: --> 
<script type="text/javascript" src="http://yui.yahooapis.com/combo?2.6.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
		<script type="text/javascript" src="alternate.js"></script>
		<title>Alternate colors</title>
	</head>
	<body>
		<table class="alternateRows">
			<tr>
				<td>First Row</td>
			</tr>
			<tr>
				<td>Second Row</td>
			</tr>
			<tr>
				<td>Third Row</td>
			</tr>
			<tr>
				<td>Fourth Row</td>
			</tr>
			<tr>
				<td>Fifth Row</td>
			</tr>
		</table>
	</body>
</html>

Invoking the javascript

To add the alternate colors to your table rows, you just have to put the following javascript code in your HTML page.

	YAHOO.util.Event.on(window, 'load', function(){
		YAHOO.htmlblog.alternateRows.init('alternateRows', '#fff', '#ccc');
	});

That means that after the page has been loaded, we call the alternateRows.init function, with 3 parameters:

  • the table class name, in our case it’s “alternateRows”
  • the first color in hex, e.g #fff
  • the second color in hex, e.g #ccc

Our complete HTML page

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<!-- Combo-handled YUI JS files: --> 
<script type="text/javascript"src="http://yui.yahooapis.com/combo?2.6.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
		<script type="text/javascript" src="alternate.js"></script>
		<script type="text/javascript">
			YAHOO.util.Event.on(window, 'load', function(){
				YAHOO.htmlblog.alternateRows.init('alternateRows', '#fff', '#ccc');
			});
		</script>
		<title>Alternate colors</title>
	</head>
	<body>
		<table class="alternateRows">
			<tr>
				<td>First Row</td>
			</tr>
			<tr>
				<td>Second Row</td>
			</tr>
			<tr>
				<td>Third Row</td>
			</tr>
			<tr>
				<td>Fourth Row</td>
			</tr>
			<tr>
				<td>Fifth Row</td>
			</tr>
		</table>
	</body>
</html>

8 practical tips to make your web pages faster

faster web pages

Yahoo’s Exceptional Performance team has compiled a list of 34 best practices to have faster web pages. In this post I’ll show you 8 tips which helped me to get a B grade in YSlow! for web pages that I develop. Currently YSlow’s web page analysis is based on 13 identified basic rules that affect web page performance. In decreasing order of priority they are:

  1. Make Fewer HTTP Requests
  2. Use a Content Delivery Network
  3. Add an Expires Header
  4. Gzip Components
  5. Put CSS at the Top
  6. Move Scripts to the Bottom
  7. Avoid CSS Expressions
  8. Make JavaScript and CSS External
  9. Reduce DNS Lookups
  10. Minify JavaScript
  11. Avoid Redirects
  12. Remove Duplicate Scripts
  13. Configure ETags

You can get more info by clicking on each item. Of course using a CDN is not affordable by everybody, including me. This didn’t prevent me to have a B grade though. I will guide you through some of the items which worked for me.


Make Fewer HTTP Requests
If you’re using the YUI library, the good news is that recently the team graciously offered a Combo Handler Service, served from their CDN. This helps us to eliminate HTTP requests by requesting a single file. For example, to use the Rich Text editor, it needed 6 separate HTTP requests:

 
 
 

 

Now with the Combo Handler service, it has been stripped to only 1 file:


If you’re not using the YUI library or not interested in using the Combo Handler service, you can try Minify!
Minify is a PHP5 app that can combine multiple CSS or Javascript files, compress their contents (i.e. removal of unnecessary whitespace/comments), and serve the results with HTTP encoding (gzip/deflate) and headers that allow optimal client-side caching.

Another tool which can be helpful is Dojo Shrinksafe which not only minifies your javascript code but also allows you to upload several javascript files and have them compressed in 1 single file.

Another way to make fewer HTTP requests is by using CSS sprites which are big images containing lots of smaller ones. An online tool which can make CSS sprites out of your smaller ones is the CSS Sprite Generator. You just have to upload your pics and it will generate your sprite together with the CSS code. More info about CSS sprites can be found on CSS Tricks.


Add an Expires Header
For this to work on Apache, you’ll need to have mod_expires enabled. Then create an .htaccess file or edit your httpd.conf with the following content:

ExpiresActive On
ExpiresByType image/jpg "access plus 2 years"
ExpiresByType image/jpeg "access plus 2 years"
ExpiresByType image/gif "access plus 2 years"
ExpiresByType application/javascript "access plus 2 years"
ExpiresByTYpe text/css "access plus 2 years"

In the above listing, all images(jpg/jpeg/gif) will have an expires header 2 years in the future.


Gzip Components
You must have mod_deflate enabled and drop these lines in your httpd.conf file

SetOutputFilter DEFLATE
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
SetEnvIfNoCase Request_URI \.(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
SetEnvIfNoCase Request_URI \.pdf$ no-gzip dont-vary

Put CSS at the Top
All CSS must be between your head tag, like that :

	
		
			
		
		
		
		
	

Move Scripts to the Bottom
While the CSS are sitting at the top of your page, javascripts must be moved towards the lower part of your page, typically in the body tag. I usually put them before the closing body tag.

	
		
		
		
		...
		...
		
		
	

Reduce DNS Lookups
I don’t usually have more than 2 DNS lookups in my scripts, else YSlow will be removing some points.


Minify JavaScript
As I mentioned earlier on, Dojo Shrinksafe is an online tool which minifies your code.

Another great command line tool is Julien Lecomte YUI Compressor.

In order to use it you must have Java installed (>= 1.4).

Douglas Crockford also has something similar in JSMin


Configure ETags
Just drop this line in your httpd.conf:

FileETag None

😉

Show/hide containers by only adding CSS classes without writing javascript code (YUI-based)

This post will show you how to add the collapse/expand functionality in your HTML pages, perfect for FAQs by only adding two class names to your existing page and including the scripts below. Of course it’s all YUI-based and also a demo of the fantastic YUI selector utility.

What does the script do ?

OK, suppose you have a FAQ page where you have traditional anchor methods, i.e you click on the question and then you go to the bottom of the page to get the answer or you get redirected to another page. But now your users are complaining your site’s not trendy enough and want to have the answer displayed immediately after clicking the question.

The solution.

After downloading the javascript file, include it at the bottom of your page with the following HTML code:

<script type="text/javascript" src="http://yui.yahooapis.com/combo?2.5.2/build/yahoo-dom-event/yahoo-dom-event.js&2.5.2/build/selector/selector-beta-min.js"></script> 
<script type="text/javascript" src="js/toggler.js"></script>

We need to include the selector utility which will be used to retrieve a collection of elements that match a given CSS selector. For e.g if we want to retrieve all div nodes in HTML page having the class “foo”, we can write :

var myNodes = YAHOO.util.Selector.query('div.foo');

The selector is used in the toggler.js file.

After adding the scripts, now you have to add CSS classes to your containers. For example for the FAQ, for questions (or main, call it whatever you want), you add the class “htmlblog-main” and for the answers (or sub), add the “htmlblog-sub” class.

Before :

<div>1. Question</div>
<div>Answer1</div>
<div>2. Question 2</div>
<div>Answer 2</div>

After :

<div class="htmlblog-main">1. Question</div>
<div class="htmlblog-sub">Answer1</div>
<div class="htmlblog-main">2. Question 2</div>
<div class="htmlblog-sub">Answer 2</div>

If you already had a class for that container, no problem you can add the htmlblog-main or htmlblog-sub class :

<div class="myclass htmlblog-main">1. Question</div>

What next ?

That’s all ! All your answer containers will be hidden and questions will have a [+] besides them. Pretty easy

Am I obliged to use the htmlblog-main and html-sub classes ? And I don’t want to use div tags, I want li tags.

Don’t worry, if you don’t like the class names you can put whatever you want but you’ll have to edit the toggler.js file at the following lines :

YAHOO.util.Event.addListener(window, 'load', function(){
	YAHOO.htmlblog.init('div', 'htmlblog-main', 'htmlblog-sub');
});

For e.g, if you’re using li tags instead of divs with the “myMainClass” as main and “mySubClass” as sub, the code goes :

YAHOO.util.Event.addListener(window, 'load', function(){
	YAHOO.htmlblog.init('li', 'myMainClass', 'mySubClass');
});

I’am getting an alert saying “Number of main and subs incorrect”.

That means the number of main/subs are not the same. You need to have the number of the main class equals the number of the sub class.

nouzil.com – a new Mauritian portal on the web (YUI-based)

I came to know the existing of a new Mauritian portal via Avinash called nouzil (which means our island in creole) and I must say at first look it reminds me of Netvibes a lot. I think the nouzil.com team picked up some bits and pieces from Netvibes.com.
Anyway, looking behind the scenes I notice that the new portal uses YUIa lot, in fact it’s all YUI-based. Had a look at the source and they are using the following YUI components (with my comments) :

  • utilities – for XHR requests, dragging of widgets, various DOM manipulations
  • cookie – to save the state of the widgets and order I presume
  • container – for various settings panels and the loading panel at the start
  • json – json data (hadn’t seen any in my Firebug panel)
  • element – ?
  • calendar – calendar widget at the bottom
  • tabview – when doing a Google search the results are displayed in a new tab
  • reset-fonts-grids – for layout, they are using the 974px width template

Unfortunately the nouzil.js was minified thus unreadable and couldn’t get very far in my analysis 😉

Overall I find the portal quite nice and find the CanalSat widget very useful since the CanalSat Reunion website is very slow and the widget shows the current programs on air. It would be interesting if the user could choose the time frame he wishes to view the programme. The Flickr widget too is cool, showing the latest photos from Mauritius and I think it’s an exact replica from that of Netvibes, so is the delicious one.

Another thing I noticed is that the team did not follow Yahoo’s performance rules for website, no caching, no gzipping and I have to download the same images again and again. I think they can improve it and take it very far, why not compete with the big boys.

Good luck to the nouzil.com team and congrats for that all YUI-basedportal.

YUI-based alert box – replace your ugly javascript alert box

This tutorial will explain how you can override the default alert box of your browser, without modifying your existing code and by adding 2 lines of javascript code.

Those 2 famous lines

After downloading the package and extracting it to your folder, add the following lines at the end of your page.

<script type="text/javascript" src="http://yui.yahooapis.com/combo?2.5.2/build/yuiloader/yuiloader-beta-min.js"></script>
<script type="text/javascript" src="js/alert.js"></script> 

We make use of YUI’s fantastic loader utility which will allows us to load specific YUI components and their dependencies into our page via script from their servers. The second file actually contains all the code which will replace the default alert box by a YUI-based and YUI-skinned one.
Note that it’s better to include the files at the bottom of your page as told earlier as recommended by Yahoo’s Exceptional Performance team for speeding your page.

The HTML code

<a href="#" onclick="alert('Hello World !');">Click to say hi</a>

That’s all, you don’t need to include any CSS or other javascript files. They are all taken from Yahoo servers and you get a nice alert message. If for one reason or another you’re fed up with this alert box, you just remove the included javascript files and it will fall back to the default alert box.

Behind the scenes.

You can open the alert.js file which is well commented to have a look at what’s going behind the scenes. Dav Glass wrote something about this replacement for alert, it’s almost the same thing except all is done through the loader utility. 😉

The alert.js file contains 2 JSON objects namely :

  • bootstrap
  • ui

bootstrap

bootstrap is responsible for fetching all the components from the Yahoo servers namely :

  • container – since we are using the SimpleDialog component to render the alert box
  • button – to have the nice button in the box
  • fonts – which offers cross-browser typographical normalization and control
  • selector – to perform some lookups to add the yui-skin-sam class to the body so as we can use YUI’s skinning system.

ui

The ui in fact initializes our SimpleDialog and then render it

// our dialog for info, to show messages to the users
ui.dialogInfo = new YAHOO.widget.SimpleDialog("simpledialog1", 
{
width: "300px",
fixedcenter: true,
visible: false,
draggable: false,
zIndex: 9999,
close: true,
modal: true,
effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.25},
constraintoviewport: true,
buttons: [ { text:"close", handler: function(){this.hide();}, isDefault:true }]
});
ui.dialogInfo.setHeader("information");
// Render the Dialog
ui.dialogInfo.render(document.body);

It also contains the showDialogInfo method which is called when alert function is called.

window.alert = function(text){
	ui.dialogInfo.setBody(text);
	ui.dialogInfo.show();
};

Expanding/collapsing javascript menu

In this post I’ll show you how to create an expanding/collapsing menu like Slashdot left menu used to be, using the YUI library and Dav GlassYUI effects widget.


The HTML markup for our menu is :

<div id="menu">
			<h1 id="menu-title">Menu</h1>
			<div id="menu-links">
				<ul>
					<li>Home</li>
					<li>About</li>
					<li>CSS</li>
				</ul>
			</div>
		</div>

We use 2 div tags, one for holding the menu itself and the other one which contains the links in an unordered list and 1 h1 tag for the title.

The CSS for the menu :

/** width of the menu */
#menu{
				width: 180px;
			}
			

/** the main title */
			#menu h1{
				line-height: 35px;
				color: #fff;
				/** simulate link */
				cursor: pointer;
				font-weight: bold;
				/** background image will change when menu expands/collapses */
				background: #666 url(images/block-arrow-expanded.gif) no-repeat scroll 30px 13px;
			}
			
/** the links */
			#menu-links li{
				line-height: 35px;
				border-bottom:1px solid #ddd;
				background-color: #eee;
			}

Please pay attention to the background for the #menu h1. It contains the image, which will change when the menu collapses or expands. When the menu collapses we’ll be using the block-arrow-collapsed.gif image and when the menu expands we’ll be using the block-arrow-expanded.gif image. You can find the images in the sample demo file in the images directory.

To do the collapsing/expanding effects, we need to include the following javascript files beforehand :

<!-- js -->
<script type="text/javascript"  src="http://yui.yahooapis.com/combo?2.5.2/build/yahoo-dom-event/yahoo-dom-event.js&2.5.2/build/animation/animation-min.js"></script> 
<script type="text/javascript" src="js/tools-min.js"></script>
<script type="text/javascript" src="js/effects-min.js"></script>

We use Dav Glass YAHOO.Tools package and his effects widget along with yahoo-dom-event-animation aggregate file which are hosted on Yahoo servers.

Finally the javascript to do the magical stuff goes like that :

<script type="text/javascript">
			YAHOO.util.Event.addListener('menu-title', 'click', function(){
				if(YAHOO.util.Dom.getStyle('menu-links', 'display') == 'block'){
					new YAHOO.widget.Effects.BlindUp('menu-links', {seconds: 0.2});
					YAHOO.util.Dom.setStyle('menu-title', 'background-image', 'url(images/block-arrow-collapsed.gif)');
				}
				else{
					new YAHOO.widget.Effects.BlindDown('menu-links', {seconds: 0.2});
					YAHOO.util.Dom.setStyle('menu-title', 'background-image', 'url(images/block-arrow-expanded.gif)');
				}
			});
		</script>

In line 3 of the above listing, we wait when the user clicks on the menu-title container and we check the display attribute of our links. If the links are not currently displayed then we display them by using Dav’s BlindDown effect with a duration of 0.2 seconds ;-).

new YAHOO.widget.Effects.BlindDown('menu-links', {seconds: 0.2});

We also change the background image for the menu title by using the YAHOO.util.Dom.setStyle method:

YAHOO.util.Dom.setStyle('menu-title', 'background-image', 'url(images/block-arrow-expanded.gif)');

If the links are visible then we do the contrary, i.e we use the BlindUp effect and use the collapsed gif as background image.

YUI-based numeric stepper widget

Since I had some problems with YUI slider, I decided to write a YUI-based numeric stepper that allows users to select values within a predefined range.

To instantiate the widget include the following files :

<!-- CSS -->
<link rel="stylesheet" type="text/css" href="stepper/stepper.css" />
		
<!-- Dependencies -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/yahoo-dom-event/yahoo-dom-event.js"></script>
		
<!-- Stepper source file -->
<script type="text/javascript" src="stepper/stepper-min.js"></script>

Then place your stepper in your body :

<div id="stepperValue">10 px</div>
<div class="stepperControls">
	<div id="stepperUp"><img src="stepper/add.gif" /></div>
	<div id="stepperDown"><img src="stepper/sub.gif" /></div>
</div>
<div style="clear:both"></div>

The stepperValue id will display the current value of the stepper.
The stepperControls will contain the different controls for our stepper, and you can place it anywhere you want and use whatever images you want.

Finally when the DOM is ready, instantiate the widget :

<script type="text/javascript">			
	YAHOO.util.Event.onDOMReady(function(){
		var mystepper = new YAHOO.widget.Stepper(10, 'stepperUp', 'stepperDown', 0, 200, 10);
		mystepper.onChange.subscribe(function(){
			YAHOO.util.Dom.get('stepperValue').innerHTML = mystepper.getValue() + ' px';
		});
</script>

The stepper takes 6 parameters, all mandatory (check source code) :

var mystepper = new YAHOO.widget.Stepper(10, 'stepperUp', 'stepperDown', 0, 200, 10);
  • 1. the initial value
  • 2. the ID of the element for the up control button
  • 3. the ID of the element for the down control button
  • 4. the minimum value the stepper can decreased to
  • 5. the maximum value the stepper can increased to
  • 6. by how much the stepper is incremented/decremented after each click

We listen for any change to the stepper and in this case, display the updated value in the container we defined earlier on ( stepperValue) using innerHTML.

mystepper.onChange.subscribe(function(){
			YAHOO.util.Dom.get('stepperValue').innerHTML = mystepper.getValue() + ' px';
		});

You can get the current value of the stepper by calling :

var currentValue = mystepper.getValue();

Simple YUI Cookie example – javascript text magnifier for your page

Since YUI 2.5.0 there’s the Cookie utility and at this time of posting, it’s still in beta version.
I’ll show you how we can use this simple utility to write a small javascript app.

The piece of code we will be writing, using the YUI library (my favorite), will allow users to increase/decrease their font size for a block of text, storing the font size in a cookie
so that when they return to the page they don’t have to modify the font size again.

You can view a live demo here.

Getting started.

Our page will consist of a block of text, along with 2 images. One to increase the font size and the other one to decrease it.
The images we’ll be using :

So the HTML goes like that :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<title>yui cookie</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	</head>
	<body>
		<div><img src="A+.gif" alt="increase font size" id="increaseFont" /></div>
		<div><img src="A-.gif" alt="decrease font size" id="decreaseFont" /></div>
		<div id="news-main">
			Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas sit amet metus.
Nunc quam elit, posuere nec, auctor in, rhoncus quis, dui. Aliquam erat volutpat. Ut dignissim, massa 	</div>
	</body>
</html>

We define unique ids for DOM manipulation afterwards.

Next, we add the necessary YUI libraries. We will be using

  • yahoo-dom-event.js (aggregated yahoo, dom, event js)
  • cookie-beta.js

hosted at the geolocated Yahoo servers.

We add these two lines of code at the end of the file, before the closing body tag, to maximise performance (more on that in a later post).

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<title>yui cookie</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	</head>
	<body>
		<div><img src="A+.gif" alt="increase font size" id="increaseFont" /></div>
		<div><img src="A-.gif" alt="decrease font size" id="decreaseFont" /></div>
		<div id="news-main">
			Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas sit amet metus.
Nunc quam elit, posuere nec, auctor in, rhoncus quis, dui. Aliquam erat volutpat. Ut dignissim, massa 	
		</div>
		
		<!-- js -->
		<script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/yahoo-dom-event/yahoo-dom-event.js"></script>
		<script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/cookie/cookie-beta-min.js"></script>
		<!-- /js -->
	</body>
</html>

Our page is almost ready we just have to write the code to update the font size. The javascript code goes like this,

var updateFontSize = function(o, params){
	try{
		if(params.type == 'increase'){
			newSize = parseInt(YAHOO.util.Dom.getStyle(params.id, 'font-size'), 10) + 1;
		}
		else{
			newSize = parseInt(YAHOO.util.Dom.getStyle(params.id, 'font-size'), 10) - 1;
		}
		
		YAHOO.util.Dom.setStyle(params.id, 'font-size', newSize + 'px');
		YAHOO.util.Cookie.set("news-size", newSize, { path: "/", expires: new Date("December 22, 2010") });
	}
	catch(e){}
};

YAHOO.util.Event.addListener('increaseFont', 'click', updateFontSize, {"id" : 'news-main', "type" : 'increase'});
YAHOO.util.Event.addListener('decreaseFont', 'click', updateFontSize, {"id" : 'news-main', "type" : 'decrease'});
YAHOO.util.Event.addListener(window, 'load', function(){
	try{
		var newsSize = YAHOO.util.Cookie.get("news-size", function(value){
	        	YAHOO.util.Dom.setStyle('news-main', 'font-size', value + 'px');
		});
	}
	catch(e){}
});

Now we let us have an extensive look at the code above.

We define a function updateFontSize which takes 2 parameters, the second one being json data we will be passing using YUI addListenermethod.
Line 3 checks whether we want to increase or decrease the font size. In any case, we get the current font size of the text using
YAHOO.util.Dom.getStyle method which will return a value of 11px for example. We then use the parseInt function to return only the integer so that
we can increase/decrease it by 1;

After getting the new size in the newSize variable, we just apply it to the block of text using the YAHOO.util.Dom.setStyle method :

YAHOO.util.Dom.setStyle(params.id, 'font-size', newSize + 'px');

the params.id being the id on which we want the style to be applied on and passed through at line 16/17 above.

Line 11 just sets the cookie for future visits, giving it a name and an expiration date.

The whole block is surrounded by try catch statement.

Listeners

In line 16 and 17 we add event listeners to the respective images, one to increase the font size, the other one to decrease it

YAHOO.util.Event.addListener('increaseFont', 'click', updateFontSize, {"id" : 'news-main', "type" : 'increase'});
YAHOO.util.Event.addListener('decreaseFont', 'click', updateFontSize, {"id" : 'news-main', "type" : 'decrease'});

For simple understanding the above code just says when someone click on the increaseFont id, call the updateFontSize function,
with the id and the type as parameters. The parameter is the JSON data I was talking earlier.

Line 18 says when the after the window has loaded completely, we try to get the news-size cookie.

YAHOO.util.Event.addListener(window, 'load', function(){
	try{
		var newsSize = YAHOO.util.Cookie.get("news-size", function(value){

If the latter doesn’t exist, it
will return false, else it returns the value in it, and we just take the value and apply it to the block of text via the YAHOO.util.Dom.setStyle method.

var newsSize = YAHOO.util.Cookie.get("news-size", function(value){
	YAHOO.util.Dom.setStyle('news-main', 'font-size', value + 'px');
}

As always we surround the block with try catch statements.

Our final code looks that that :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<title>yui cookie</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	</head>
	<body>
		<div><img src="A+.gif" alt="increase font size" id="increaseFont" /></div>
		<div><img src="A-.gif" alt="decrease font size" id="decreaseFont" /></div>
		<div id="news-main">
			Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas sit amet metus.
Nunc quam elit, posuere nec, auctor in, rhoncus quis, dui. Aliquam erat volutpat. Ut dignissim, massa 	
		</div>
		
		<!-- js -->
		<script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/yahoo-dom-event/yahoo-dom-event.js"></script>
		<script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/cookie/cookie-beta-min.js"></script>
		<!-- /js -->

		<script type="text/javascript">
		var updateFontSize = function(o, params){
			try{
				if(params.type == 'increase'){
					newSize = parseInt(YAHOO.util.Dom.getStyle(params.id, 'font-size'), 10) + 1;
				}
				else{
					newSize = parseInt(YAHOO.util.Dom.getStyle(params.id, 'font-size'), 10) - 1;
				}
		
				YAHOO.util.Dom.setStyle(params.id, 'font-size', newSize + 'px');
				YAHOO.util.Cookie.set("news-size", newSize, { path: "/", expires: new Date("December 22, 2010") });
			}
			catch(e){}
		};

		YAHOO.util.Event.addListener('increaseFont', 'click', updateFontSize, {"id" : 'news-main', "type" : 'increase'});
		YAHOO.util.Event.addListener('decreaseFont', 'click', updateFontSize, {"id" : 'news-main', "type" : 'decrease'});
		YAHOO.util.Event.addListener(window, 'load', function(){
			try{
				var newsSize = YAHOO.util.Cookie.get("news-size", function(value){
	        			YAHOO.util.Dom.setStyle('news-main', 'font-size', value + 'px');
				});
			}
			catch(e){}
		});
		</script>
	</body>
</html>

Of course all this can be done with using the YUI library, but it’s my fav. 😉

Be Sociable, Share!