<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tutorialzine &#187; CSS</title>
	<atom:link href="http://tutorialzine.com/category/tutorials/css-tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://tutorialzine.com</link>
	<description>Web Development Tutorials &#38; Resources</description>
	<lastBuildDate>Wed, 01 Feb 2012 14:50:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Making a jQuery Countdown Timer</title>
		<link>http://tutorialzine.com/2011/12/countdown-jquery/</link>
		<comments>http://tutorialzine.com/2011/12/countdown-jquery/#comments</comments>
		<pubDate>Fri, 30 Dec 2011 11:02:06 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1781</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2011/12/countdown-jquery/"><img src="http://cdn.tutorialzine.com/img/featured/1781.jpg" /></a></div> Today we are going to build a neat jQuery plugin for displaying a countdown timer. It will show the remaining days, hours, minutes and seconds to your event, as well as an animated updates on every second.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2011/12/countdown-jquery/"><img src="http://cdn.tutorialzine.com/img/featured/1781.jpg" /></a></div> <p>When building a <a title="Creating a Stylish Coming Soon Page with jQuery" href="http://tutorialzine.com/2010/10/ajaxed-coming-soon-page/">coming soon</a> or event page, you find yourself in search for a good way to display the remaining time. A countdown gives the feel of urgency, and combined with an email field will yield more signups for your newsletter.</p>
<p>Today we are going to build a neat jQuery plugin for displaying a countdown timer. It will show the remaining days, hours, minutes and seconds to your event, as well as an animated updates on every second. <strong>Note:</strong> the plugin is also available on <a href="https://github.com/martinaglv/jQuery-Countdown" target="_blank">Github</a>.</p>
<p>Let&#8217;s start with the markup!</p>
<h3>The HTML</h3>
<p>We will give the plugin the creative name of &#8220;countdown&#8221;. Called on an empty element, it will fill it with the HTML that is needed for the countdown timer. You don&#8217;t need to do anything but choose the element in which you want to show it.</p>
<h4>Generated markup</h4>
<pre class="brush:html">&lt;div id="countdown" class="countdownHolder"&gt;
	&lt;span class="countDays"&gt;
		&lt;span class="position"&gt;
			&lt;span class="digit static"&gt;&lt;/span&gt;
		&lt;/span&gt;
		&lt;span class="position"&gt;
			&lt;span class="digit static"&gt;&lt;/span&gt;
		&lt;/span&gt;
	&lt;/span&gt;

	&lt;span class="countDiv countDiv0"&gt;&lt;/span&gt;

	&lt;span class="countHours"&gt;
		&lt;span class="position"&gt;
			&lt;span class="digit static"&gt;&lt;/span&gt;
		&lt;/span&gt;
		&lt;span class="position"&gt;
			&lt;span class="digit static"&gt;&lt;/span&gt;
		&lt;/span&gt;
	&lt;/span&gt;

	&lt;span class="countDiv countDiv1"&gt;&lt;/span&gt;

	&lt;span class="countMinutes"&gt;
		&lt;span class="position"&gt;
			&lt;span class="digit static"&gt;&lt;/span&gt;
		&lt;/span&gt;
		&lt;span class="position"&gt;
			&lt;span class="digit static"&gt;&lt;/span&gt;
		&lt;/span&gt;
	&lt;/span&gt;

	&lt;span class="countDiv countDiv2"&gt;&lt;/span&gt;

	&lt;span class="countSeconds"&gt;
		&lt;span class="position"&gt;
			&lt;span class="digit static"&gt;&lt;/span&gt;
		&lt;/span&gt;
		&lt;span class="position"&gt;
			&lt;span class="digit static"&gt;&lt;/span&gt;
		&lt;/span&gt;
	&lt;/span&gt;

	&lt;span class="countDiv countDiv3"&gt;&lt;/span&gt;
&lt;/div&gt;</pre>
<p>In the above example, the plugin has been originally called on a div with an id of <strong>countdown</strong>. The plugin has then added a <strong>countdownHolder</strong> class to it (so a few styles are applied to the element via CSS).</p>
<p>Inside is the markup for the digits. There are two <strong>digit</strong> spans for every time unit (days, hours, minutes and seconds), which means that you can count down towards a date that is no more than 99 days in the future (for such time frames you should probably not use the timer anyway, it would be discouraging).</p>
<p>The static class of the digits gives them their gradient background and box-shadow. When animated, this class is removed so that these CSS3 touches don&#8217;t slow down the animation. The digits are brought together in groups so you can easily style them. Adding a font-size declaration to .<strong>countDays</strong>, will affect the size of both day digits.</p>
<div id="attachment_1782" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/12/countdown-jquery/"><img class="size-full wp-image-1782" title="A jQuery Countdown Timer" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/12/jquery-countdown-timer.jpg" alt="A jQuery Countdown Timer" width="620" height="260" /></a><p class="wp-caption-text">A jQuery Countdown Timer</p></div>
<p>The <strong>.countDiv</strong> spans are the dividers between the units. The colon is formed with :before/:after elements.</p>
<p>But how is this markup generated exactly?</p>
<h3>The jQuery</h3>
<p>First let&#8217;s write two helper functions used by the plugin:</p>
<ul>
<li><strong>init</strong> generates the markup you saw above;</li>
<li><strong>switchDigit</strong> takes a .position span and animates the digits inside it;</li>
</ul>
<p>Extracting this functionality as separate functions allows us to keep the plugin code clean.</p>
<h4>assets/countdown/jquery.countdown.js</h4>
<pre class="brush:js">	function init(elem, options){
		elem.addClass('countdownHolder');

		// Creating the markup inside the container
		$.each(['Days','Hours','Minutes','Seconds'],function(i){
			$('&lt;span class="count'+this+'"&gt;').html(
				'&lt;span class="position"&gt;\
					&lt;span class="digit static"&gt;0&lt;/span&gt;\
				&lt;/span&gt;\
				&lt;span class="position"&gt;\
					&lt;span class="digit static"&gt;0&lt;/span&gt;\
				&lt;/span&gt;'
			).appendTo(elem);

			if(this!="Seconds"){
				elem.append('&lt;span class="countDiv countDiv'+i+'"&gt;&lt;/span&gt;');
			}
		});

	}

	// Creates an animated transition between the two numbers
	function switchDigit(position,number){

		var digit = position.find('.digit')

		if(digit.is(':animated')){
			return false;
		}

		if(position.data('digit') == number){
			// We are already showing this number
			return false;
		}

		position.data('digit', number);

		var replacement = $('&lt;div&gt;',{
			'class':'digit',
			css:{
				top:'-2.1em',
				opacity:0
			},
			html:number
		});

		// The .static class is added when the animation
		// completes. This makes it run smoother.

		digit
			.before(replacement)
			.removeClass('static')
			.animate({top:'2.5em',opacity:0},'fast',function(){
				digit.remove();
			})

		replacement
			.delay(100)
			.animate({top:0,opacity:1},'fast',function(){
				replacement.addClass('static');
			});
	}</pre>
<p>Great! Now let&#8217;s move on with the plugin body. Our plugin must take an object with parameters for better configurability &#8211; a timestamp of the period we are counting towards, and a callback function, executed on every tick and passed the remaining time. For brevity, I&#8217;ve omitted the functions above from the code.</p>
<h4>assets/countdown/jquery.countdown.js</h4>
<pre class="brush:js">(function($){

	// Number of seconds in every time division
	var days	= 24*60*60,
		hours	= 60*60,
		minutes	= 60;

	// Creating the plugin
	$.fn.countdown = function(prop){

		var options = $.extend({
			callback	: function(){},
			timestamp	: 0
		},prop);

		var left, d, h, m, s, positions;

		// Initialize the plugin
		init(this, options);

		positions = this.find('.position');

		(function tick(){

			// Time left
			left = Math.floor((options.timestamp - (new Date())) / 1000);

			if(left &lt; 0){
				left = 0;
			}

			// Number of days left
			d = Math.floor(left / days);
			updateDuo(0, 1, d);
			left -= d*days;

			// Number of hours left
			h = Math.floor(left / hours);
			updateDuo(2, 3, h);
			left -= h*hours;

			// Number of minutes left
			m = Math.floor(left / minutes);
			updateDuo(4, 5, m);
			left -= m*minutes;

			// Number of seconds left
			s = left;
			updateDuo(6, 7, s);

			// Calling an optional user supplied callback
			options.callback(d, h, m, s);

			// Scheduling another call of this function in 1s
			setTimeout(tick, 1000);
		})();

		// This function updates two digit positions at once
		function updateDuo(minor,major,value){
			switchDigit(positions.eq(minor),Math.floor(value/10)%10);
			switchDigit(positions.eq(major),value%10);
		}

		return this;
	};

	/* The two helper functions go here */</pre>
<pre class="brush:js">})(jQuery);</pre>
<p>The tick function calls itself every second. Inside it, we calculate the time difference between the given timestamp and the current date. The <strong>updateDuo</strong> function then updates the digits comprising the time unit.</p>
<p><strong>The plugin is ready!</strong> Here is how to use it (as seen in the demo):</p>
<h4>assets/js/script.js</h4>
<pre class="&quot;brush:js">$(function(){

	var note = $('#note'),
		ts = new Date(2012, 0, 1),
		newYear = true;

	if((new Date()) &gt; ts){
		// The new year is here! Count towards something else.
		// Notice the *1000 at the end - time must be in milliseconds
		ts = (new Date()).getTime() + 10*24*60*60*1000;
		newYear = false;
	}

	$('#countdown').countdown({
		timestamp	: ts,
		callback	: function(days, hours, minutes, seconds){

			var message = "";

			message += days + " day" + ( days==1 ? '':'s' ) + ", ";
			message += hours + " hour" + ( hours==1 ? '':'s' ) + ", ";
			message += minutes + " minute" + ( minutes==1 ? '':'s' ) + " and ";
			message += seconds + " second" + ( seconds==1 ? '':'s' ) + " &lt;br /&gt;";

			if(newYear){
				message += "left until the new year!";
			}
			else {
				message += "left to 10 days from now!";
			}

			note.html(message);
		}
	});

});</pre>
<p>Of course, for this to work, you will have to include the css and js file from the countdown folder in your page.</p>
<h3>Done!</h3>
<p>You can use this script as the perfect addition to every launch page. The best thing about it is that it doesn&#8217;t use a single image, everything is done with CSS alone. Increasing or decreasing the font size will result in everything scaling nicely, and you only need a <strong>display:none</strong> declaration to hide the units you don&#8217;t need.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/12/countdown-jquery/feed/</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
		<item>
		<title>Shiny Knob Control with jQuery and CSS3</title>
		<link>http://tutorialzine.com/2011/11/pretty-switches-css3-jquery/</link>
		<comments>http://tutorialzine.com/2011/11/pretty-switches-css3-jquery/#comments</comments>
		<pubDate>Wed, 30 Nov 2011 15:00:50 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1689</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2011/11/pretty-switches-css3-jquery/"><img src="http://cdn.tutorialzine.com/img/featured/1689.jpg" /></a></div> In this tutorial we will be writing a jQuery plugin for creating a shiny knob control, suitable for use in control panels and other administrative pages.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2011/11/pretty-switches-css3-jquery/"><img src="http://cdn.tutorialzine.com/img/featured/1689.jpg" /></a></div> <p>In this tutorial we will be writing a jQuery plugin for creating a shiny knob control. Aptly named knobKnob, this plugin will use CSS3 transformations and jQuery&#8217;s new event handling methods to give visitors of your website a new way of interactively choosing a value from a range.</p>
<p><a href="https://github.com/martinaglv/KnobKnob" target="_blank">KnobKnob is also on Github.</a></p>
<p><strong>Update:</strong> Thanks to <a href="https://github.com/ranyefet" target="_blank">ranyefet</a> the plugin now works on mobile devices [<a href="https://github.com/martinaglv/KnobKnob/commit/76fb3845e4f70dd8509c4a7d5f45dfe3d4e10b28" target="_blank">changes</a>].</p>
<h3>The HTML</h3>
<p>The HTML markup for the page is rather straightforward. We are only going to need a placeholder element for the control &#8211; the rest is going to be dynamically generated by the plugin. Just in case, here is the complete markup of the page:</p>
<h4>index.html</h4>
<pre class="brush:html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta charset="utf-8" /&gt;
        &lt;title&gt;Shiny Switches with CSS3 &amp;amp; jQuery | Tutorialzine Demo&lt;/title&gt;

        &lt;!-- CSS stylesheets --&gt;
        &lt;link rel="stylesheet" href="assets/css/styles.css" /&gt;
        &lt;link rel="stylesheet" href="assets/knobKnob/knobKnob.css" /&gt;

        &lt;!--[if lt IE 9]&gt;
          &lt;script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt;
        &lt;![endif]--&gt;
    &lt;/head&gt;

    &lt;body&gt;

		&lt;section id="main"&gt;

			&lt;div id="bars"&gt;
				&lt;div id="control"&gt;
					&lt;!-- The knob markup will go here --&gt;
				&lt;/div&gt;
                                &lt;!-- The colorful dividers will go here --&gt;
			&lt;/div&gt;

		&lt;/section&gt;

        &lt;!-- JavaScript includes --&gt;
		&lt;script src="http://code.jquery.com/jquery-1.7.1.min.js"&gt;&lt;/script&gt;
		&lt;script src="assets/knobKnob/transform.js"&gt;&lt;/script&gt;
		&lt;script src="assets/knobKnob/knobKnob.jquery.js"&gt;&lt;/script&gt;
		&lt;script src="assets/js/script.js"&gt;&lt;/script&gt;

    &lt;/body&gt;
&lt;/html&gt;</pre>
<p>First we include the latest version of jQuery, <a href="https://github.com/louisremi/jquery.transform.js" target="_blank">transform.js</a> which levels cross-browser support of the CSS3 transform properties we will be using, the knobKnob plugin file and script.js, which pulls everything together.</p>
<p>The #control div is where the plugin markup will be generated. Below we will insert divs that will become the colorful bars around it. They are not part of the KnobKnob plugin, we will be showing them depending on the chosen value in the control. KnobKnob also comes with a stylesheet that determines the looks of the knob. You can see it included in the head section.</p>
<p>Now lets write this plugin!</p>
<div id="attachment_1697" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/11/pretty-switches-css3-jquery/"><img class="size-full wp-image-1697" title="Shiny Knob Control" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/11/shiny-switch-rotation.jpg" alt="Shiny Knob Control" width="620" height="354" /></a><p class="wp-caption-text">Shiny Knob Control</p></div>
<h3>The jQuery Code</h3>
<p>You can find the plugin source files in the knobKnob folder. To use it in your project simply unzip it in your website&#8217;s assets folder and include the files you find inside. Here is the actual plugin file:</p>
<h4>assets/knobKnob/knobKnob.jquery.js</h4>
<pre class="brush:js">/**
 * @name		jQuery KnobKnob plugin
 * @author		Martin Angelov
 * @version 	1.0
 * @url			http://tutorialzine.com/2011/11/pretty-switches-css3-jquery/
 * @license		MIT License
 */

(function($){

	$.fn.knobKnob = function(props){

		var options = $.extend({
			snap: 0,
			value: 0,
			turn: function(){}
		}, props || {});

		var tpl = '&lt;div class="knob"&gt;\
				&lt;div class="top"&gt;&lt;/div&gt;\
				&lt;div class="base"&gt;&lt;/div&gt;\
			&lt;/div&gt;';

		return this.each(function(){

			var el = $(this);
			el.append(tpl);

			var knob = $('.knob',el)
				knobTop = knob.find('.top'),
				startDeg = -1,
				currentDeg = 0,
				rotation = 0,
				lastDeg = 0,
				doc = $(document);

			if(options.value &gt; 0 &amp;&amp; options.value &lt;= 359){
				rotation = currentDeg = options.value;
				knobTop.css('transform','rotate('+(currentDeg)+'deg)');
				options.turn(currentDeg/359);
			}

			knob.on('mousedown', function(e){

				e.preventDefault();

				var offset = knob.offset();
				var center = {
					y : offset.top + knob.height()/2,
					x: offset.left + knob.width()/2
				};

				var a, b, deg, tmp,
					rad2deg = 180/Math.PI;

				knob.on('mousemove.rem',function(e){

					a = center.y - e.pageY;
					b = center.x - e.pageX;
					deg = Math.atan2(a,b)*rad2deg;

					// we have to make sure that negative
					// angles are turned into positive:
					if(deg&lt;0){
						deg = 360 + deg;
					}

					// Save the starting position of the drag
					if(startDeg == -1){
						startDeg = deg;
					}

					// Calculating the current rotation
					tmp = Math.floor((deg-startDeg) + rotation);

					// Making sure the current rotation
					// stays between 0 and 359
					if(tmp &lt; 0){
						tmp = 360 + tmp;
					}
					else if(tmp &gt; 359){
						tmp = tmp % 360;
					}

					// Snapping in the off position:
					if(options.snap &amp;&amp; tmp &lt; options.snap){
						tmp = 0;
					}

					// This would suggest we are at an end position;
					// we need to block further rotation.
					if(Math.abs(tmp - lastDeg) &gt; 180){
						return false;
					}

					currentDeg = tmp;
					lastDeg = tmp;

					knobTop.css('transform','rotate('+(currentDeg)+'deg)');
					options.turn(currentDeg/359);
				});

				doc.on('mouseup.rem',function(){
					knob.off('.rem');
					doc.off('.rem');

					// Saving the current rotation
					rotation = currentDeg;

					// Marking the starting degree as invalid
					startDeg = -1;
				});

			});
		});
	};

})(jQuery);</pre>
<p>The plugin takes a number of options as a parameter object &#8211; snap, value and turn:</p>
<ul>
<li><strong>snap</strong> is a number of degrees that are snapped to zero. You can test this by slowly turning the knob down;</li>
<li><strong>value</strong> is the initial rotation of the knob (also in degrees);</li>
<li><strong>turn</strong> is a callback function that is called every time the knob is turned. Its only argument is a ratio (from 0 to 1) of the rotation. We will use this function in a moment to determine how many of the colorful dividers to show.</li>
</ul>
<p>In the code above you can see that we are using the Math.atan2 function (as we did in the <a title="jQuery PointPoint – A Plugin For Pointing To Things" href="http://tutorialzine.com/2011/09/jquery-pointpoint-plugin/">PointPoint plugin</a>) to calculate the angle (in radians) between the mouse pointer and the center of the knob. By keeping track of the angle in the start and end position of the drag, we can determine how much to rotate the knob.</p>
<p>Later we are also using jQuery 1.7&#8242;s new methods for manipulating event listeners &#8211; <a href="http://api.jquery.com/on/" target="_blank">on</a> and <a href="http://api.jquery.com/off/" target="_blank">off</a>.</p>
<p>Now lets see how we can use this plugin.</p>
<h4>assets/js/script.js</h4>
<pre class="brush:js">$(function(){

	var colors = [
		'26e000','2fe300','37e700','45ea00','51ef00',
		'61f800','6bfb00','77ff02','80ff05','8cff09',
		'93ff0b','9eff09','a9ff07','c2ff03','d7ff07',
		'f2ff0a','fff30a','ffdc09','ffce0a','ffc30a',
		'ffb509','ffa808','ff9908','ff8607','ff7005',
		'ff5f04','ff4f03','f83a00','ee2b00','e52000'
	];

	var rad2deg = 180/Math.PI;
	var deg = 0;
	var bars = $('#bars');

	for(var i=0;i&lt;colors.length;i++){

		deg = i*12;

		// Create the colorbars

		$('&lt;div class="colorBar"&gt;').css({
			backgroundColor: '#'+colors[i],
			transform:'rotate('+deg+'deg)',
			top: -Math.sin(deg/rad2deg)*80+100,
			left: Math.cos((180 - deg)/rad2deg)*80+100,
		}).appendTo(bars);
	}

	var colorBars = bars.find('.colorBar');
	var numBars = 0, lastNum = -1;

	$('#control').knobKnob({
		snap : 10,
		value: 154,
		turn : function(ratio){
			numBars = Math.round(colorBars.length*ratio);

			// Update the dom only when the number of active bars
			// changes, instead of on every move

			if(numBars == lastNum){
				return false;
			}
			lastNum = numBars;

			colorBars.removeClass('active').slice(0, numBars).addClass('active');
		}
	});

});</pre>
<p>The colorful bars that are displayed around the knob are not part of the plugin. And they shouldn&#8217;t be &#8211; the plugin only handles the control itself which makes it easier to reuse it.</p>
<p>The code above creates a set of 30 divs with colors gradually going from green to red. These are then rotated by 12 degree increments. Thanks to the <strong>turn</strong> callback function passed to the plugin, this code can determine how many of the colorful bars to show. You can see the rest of the bar styling in <em>assets/css/styles.css</em>.</p>
<h3>We are done!</h3>
<p>With this our plugin is complete! You can use it as part of control panels and other administrative pages, everywhere you want to give users the ability to choose from a pool of values. Next time <a title="What You Need To Know About The HTML5 Slider Element" href="http://tutorialzine.com/2011/12/what-you-need-to-know-html5-range-input/">we will use this plugin to enhance the new range form element</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/11/pretty-switches-css3-jquery/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>Chained AJAX Selects</title>
		<link>http://tutorialzine.com/2011/11/chained-ajax-selects-jquery/</link>
		<comments>http://tutorialzine.com/2011/11/chained-ajax-selects-jquery/#comments</comments>
		<pubDate>Thu, 03 Nov 2011 15:40:06 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1662</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2011/11/chained-ajax-selects-jquery/"><img src="http://cdn.tutorialzine.com/img/featured/1662.jpg" /></a></div> In today's tutorial, we will build a set of chained select elements. Selecting an option in one of them will trigger an update on the page, showing you more choices to refine your selection.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2011/11/chained-ajax-selects-jquery/"><img src="http://cdn.tutorialzine.com/img/featured/1662.jpg" /></a></div> <p>In today&#8217;s tutorial, we will build a set of chained select elements. Selecting an option in one of them will trigger an update on the page, showing you more choices to refine your selection. We will describe the options server side with PHP, so it is easy for you to hook today&#8217;s example to a database.</p>
<p>The idea for this tutorial was suggested by <a href="http://www.crea-aalborg.dk/" target="_blank">Casper Hansen</a> from Denmark.</p>
<h3>The HTML</h3>
<p>As you can see from the screenshot below, the select box is accompanied by a title that explains what the selection is about. The title and the selectbox are enclosed in a LI item.</p>
<div id="attachment_1671" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/11/chained-ajax-selects-jquery/"><img class="size-full wp-image-1671" title="Chained AJAX Selects with jQuery and PHP" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/11/chained-ajax-selects-jquery-php.jpg" alt="Chained AJAX Selects with jQuery and PHP" width="620" height="460" /></a><p class="wp-caption-text">Chained AJAX Selects with jQuery and PHP</p></div>
<p>When adding more questions, additional LIs are created by jQuery. All of these sit inside an unordered list called <strong>#questions</strong>. The title and options for these items are served as JSON, as you will see in the PHP part of the tut. Here is the markup that is generated for the li items:</p>
<h4>index.html &#8211; generated code</h4>
<pre class="brush:html">&lt;ul id="questions"&gt;
	&lt;!-- Generated by jQuery --&gt;
	&lt;li&gt;
		&lt;p&gt;What would you like to purchase?&lt;/p&gt;
		&lt;select data-placeholder="Choose a product category"&gt;
			&lt;option data-connection="phoneSelect" value="Phones"&gt;Phones&lt;/option&gt;
			&lt;option data-connection="notebookSelect" value="Notebooks"&gt;Notebooks&lt;/option&gt;
			&lt;option data-connection="tabletSelect" value="Tablets"&gt;Tablets&lt;/option&gt;
		&lt;/select&gt;
	&lt;/li&gt;
	&lt;!-- The next sections are inserted here depending on the choices above --&gt;
&lt;/ul&gt;</pre>
<p>You might notice in the demo page that we aren&#8217;t using the default browser select controls. This is because we are making use of the <a href="http://harvesthq.github.com/chosen/" target="_blank">Chosen jQuery plugin</a> to upgrade our selects into the fancy widgets you see. We simply need to call the <strong>chosen()</strong> method on the selects, and the plugin will handle the rest.</p>
<h3>The jQuery code</h3>
<p>Here is what our jQuery code does in short &#8211; it fetches the select boxes information as JSON from the server, generates their HTML, and sets up event listeners for selection changes. If a change in the selection does occur, the process is repeated for the new select item.</p>
<p>In the code, this is achieved using two JavaScript functions:</p>
<ul>
<li><strong>refreshSelects</strong> triggers the Chosen plugin and binds event listeners every time an item is added to the page;</li>
<li><strong>fetchSelect</strong> requests a JSON feed from the server and generates the markup from the response.</li>
</ul>
<p>You can see them below.</p>
<h4>assets/js/script.js</h4>
<pre class="brush:javascript">$(function(){

	var questions = $('#questions');

	function refreshSelects(){
		var selects = questions.find('select');

		// Improve the selects with the Chose plugin
		selects.chosen();

		// Listen for changes
		selects.unbind('change').bind('change',function(){

			// The selected option
			var selected = $(this).find('option').eq(this.selectedIndex);
			// Look up the data-connection attribute
			var connection = selected.data('connection');

			// Removing the li containers that follow (if any)
			selected.closest('#questions li').nextAll().remove();

			if(connection){
				fetchSelect(connection);
			}

		});
	}

	var working = false;

	function fetchSelect(val){

		if(working){
			return false;
		}
		working = true;

		$.getJSON('ajax.php',{key:val},function(r){

			var connection, options = '';

			$.each(r.items,function(k,v){
				connection = '';
				if(v){
					connection = 'data-connection="'+v+'"';
				}

				options+= '&lt;option value="'+k+'" '+connection+'&gt;'+k+'&lt;/option&gt;';
			});

			if(r.defaultText){

				// The chose plugin requires that we add an empty option
				// element if we want to display a "Please choose" text

				options = '&lt;option&gt;&lt;/option&gt;'+options;
			}

			// Building the markup for the select section

			$('&lt;li&gt;\
				&lt;p&gt;'+r.title+'&lt;/p&gt;\
				&lt;select data-placeholder="'+r.defaultText+'"&gt;\
					'+ options +'\
				&lt;/select&gt;\
				&lt;span class="divider"&gt;&lt;/span&gt;\
			&lt;/li&gt;').appendTo(questions);

			refreshSelects();

			working = false;
		});

	}

	$('#preloader').ajaxStart(function(){
		$(this).show();
	}).ajaxStop(function(){
		$(this).hide();
	});

	// Initially load the product select
	fetchSelect('productSelect');
});</pre>
<p>Great! We are now left with generating the actual JSON feed. Notice that the <strong>fetchSelect</strong> function takes a string argument. This is the key we will be passing back to PHP, denoting which set of items we want.</p>
<p>Here is a sample response from our PHP script:</p>
<pre class="brush:js">{
    "items": {
        "Phones": "phoneSelect",
        "Notebooks": "notebookSelect",
        "Tablets": ""
    },
    "title": "What would you like to purchase?",
    "defaultText": "Choose a product category"
}</pre>
<p><strong>fetchSelect</strong> loops through the items and uses the keys as content of the option elements, and the values as connections. Phones and Notebooks would cause the script to generate new select boxes, while Tablets would not.</p>
<div id="attachment_1672" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/11/chained-ajax-selects-jquery/"><img class="size-full wp-image-1672" title="Improved Select boxes using the Chosen Plugin" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/11/chosen-selectbox.jpg" alt="Improved Select boxes using the Chosen Plugin" width="620" height="260" /></a><p class="wp-caption-text">Improved Select boxes using the Chosen Plugin</p></div>
<h3>The PHP</h3>
<p>We need to somehow store the information about the select boxes, the options they contain and the connections between them. With a database this could be done by selecting a specific set of rows. But here we will be storing this data statically as objects. For this purpose, we will define a simple class that will hold the information for a select box:</p>
<h4>ajax.php / 1</h4>
<pre class="brush:php">// Each select box will be an instance of this class

class SelectBox{
	public $items = array();
	public $defaultText = '';
	public $title = '';

	public function __construct($title, $default){
		$this-&gt;defaultText = $default;
		$this-&gt;title = $title;
	}

	public function addItem($name, $connection = NULL){
		$this-&gt;items[$name] = $connection;
		return $this;
	}

	public function toJSON(){
		return json_encode($this);
	}
}</pre>
<p>Now we only need to create an instance of this class for every select box, and call the <strong>addItem()</strong> to add options. This method has an optional <span style="text-decoration: underline;">$connection</span> parameter, that holds the name of a dependent select box.</p>
<h4>ajax.php / 2</h4>
<pre class="brush:php">/* Configuring the selectboxes */

// Product selectbox

$productSelect = new SelectBox('What would you like to purchase?','Choose a product category');
$productSelect-&gt;addItem('Phones','phoneSelect')
			  -&gt;addItem('Notebooks','notebookSelect')
			  -&gt;addItem('Tablets','tabletSelect');

// Phone types

$phoneSelect = new SelectBox('What kind of phone are you interested in?', 'Pick a phone type');
$phoneSelect-&gt;addItem('Smartphones','smartphoneSelect')
			-&gt;addItem('Feature phones','featurephoneSelect');

// Smartphones

$smartphoneSelect = new SelectBox('Which is your desired smartphone?','Choose a smartphone model');
$smartphoneSelect-&gt;addItem('Samsung Galaxy Nexus')
				 -&gt;addItem('iPhone 4S','iphoneSelect')
				 -&gt;addItem('Samsung Galaxy S2')
				 -&gt;addItem('HTC Sensation');

// Feature phones

$featurephoneSelect = new SelectBox('Which is your desired featurephone?','Choose a feature phone');
$featurephoneSelect-&gt;addItem('Nokia N34')
				   -&gt;addItem('Sony Ericsson 334')
				   -&gt;addItem('Motorola');

// iPhone colors

$iphoneSelect = new SelectBox('What color would you like?','Choose a color');
$iphoneSelect-&gt;addItem('White')-&gt;addItem('Black');

// Notebook select

$notebookSelect = new SelectBox('Which notebook would you like to buy?', 'Choose a notebook model');
$notebookSelect-&gt;addItem('Asus Zenbook','caseSelect')
			   -&gt;addItem('Macbook Air','caseSelect')
			   -&gt;addItem('Acer Aspire','caseSelect')
			   -&gt;addItem('Lenovo Thinkpad','caseSelect')
			   -&gt;addItem('Dell Inspiron','caseSelect');

// Tablet select

$tabletSelect = new SelectBox('Which tablet would you like to buy?', 'Pick a tablet');
$tabletSelect-&gt;addItem('Asus Transformer','caseSelect')
			 -&gt;addItem('Samsung Galaxy Tab','caseSelect')
			 -&gt;addItem('iPad 16GB','caseSelect')
			 -&gt;addItem('iPad 32GB','caseSelect')
			 -&gt;addItem('Acer Iconia Tab','caseSelect');

// Case select

$caseSelect = new SelectBox('Buy protective casing?','');
$caseSelect-&gt;addItem('Yes')-&gt;addItem('No');

// Register all the select items in an array

$selects = array(
	'productSelect'			=&gt; $productSelect,
	'phoneSelect'			=&gt; $phoneSelect,
	'smartphoneSelect'		=&gt; $smartphoneSelect,
	'featurephoneSelect'	=&gt; $featurephoneSelect,
	'iphoneSelect'			=&gt; $iphoneSelect,
	'notebookSelect'		=&gt; $notebookSelect,
	'tabletSelect'			=&gt; $tabletSelect,
	'caseSelect'			=&gt; $caseSelect
);</pre>
<p>The code above defines a number of select items and places them in the <strong>$selects</strong> array. When this script receives an AJAX request, it will look into this array and return a response:</p>
<h4>ajax.php / 3</h4>
<pre class="brush:php">// We look up this array and return a select object depending
// on the $_GET['key'] parameter passed by jQuery

// You can modify it to select results from a database instead

if(array_key_exists($_GET['key'],$selects)){
	header('Content-type: application/json');
	echo $selects[$_GET['key']]-&gt;toJSON();
}
else{
	header("HTTP/1.0 404 Not Found");
	header('Status: 404 Not Found');
}</pre>
<p>By calling the <strong>toJSON()</strong> method we defined in the beginning, we output all the data for the select object as JSON, ready for use by our jQuery frontend.</p>
<p><strong>With this our Chained AJAX Selects example is complete!</strong></p>
<h3>Done</h3>
<p>You can use this example to power user guides, product recommendations or search pages. Upgrading the script to use a live database is straightforward and it will actually simplify the PHP script.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/11/chained-ajax-selects-jquery/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Creating an iOS-like Home Screen with CoffeeScript</title>
		<link>http://tutorialzine.com/2011/10/ios-homescreen-coffeescript/</link>
		<comments>http://tutorialzine.com/2011/10/ios-homescreen-coffeescript/#comments</comments>
		<pubDate>Thu, 20 Oct 2011 10:46:33 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[CoffeeScript]]></category>
		<category><![CDATA[CSS]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1649</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2011/10/ios-homescreen-coffeescript/"><img src="http://cdn.tutorialzine.com/img/featured/1649.jpg" /></a></div> Today we are going to create an iOS-like home screen using CoffeeScript, and the jQuery library. For handling of touch events, we will use the touchable plugin.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2011/10/ios-homescreen-coffeescript/"><img src="http://cdn.tutorialzine.com/img/featured/1649.jpg" /></a></div> <p>Today we are going to create an iOS-like home screen using CoffeeScript &#8211; a new JavaScript based language, and the jQuery library. CoffeScript has a clean syntax that lies somewhere in between Ruby and Python. If you haven&#8217;t used any of them, don&#8217;t worry &#8211; it is not required. However you will need to be familiar with JavaScript so you can better understand the concepts behind the language.</p>
<p>We are also going to use the <a href="https://github.com/dotmaster/Touchable-jQuery-Plugin" target="_blank">Touchable</a> plugin, so we can listen for touch-based events.</p>
<h3>First, what is CoffeeScript?</h3>
<p><a href="http://jashkenas.github.com/coffee-script/" target="_blank">CoffeeScript</a> is a neat programming language meant to enhance the good parts of JavaScript, while working around the not so good. It makes OOP easy and introduces a number of useful additions such as comprehensions, new syntax for functions and scope handling, along with numerous small improvements.</p>
<p>CoffeeScript works in every browser out there, and is compatible with all your existing JavaScript code (including libraries like jQuery and plugins). But how does this work if it is a different language? Simple &#8211; <strong>CoffeeScript compiles down to JavaScript</strong>, so it works in any browser that supports it.</p>
<p>Before you start following this tutorial, I would suggest that you read through the examples on the <a href="http://jashkenas.github.com/coffee-script/" target="_blank">CoffeeScript website</a> (be sure to check out the &#8220;<strong><em>Try CoffeeScript</em></strong>&#8221; tab), and <a href="http://arcturo.github.com/library/coffeescript/index.html" target="_blank">The Little Book on CoffeeScript</a> for an introduction to the language.</p>
<div id="attachment_1655" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/10/ios-homescreen-coffeescript/"><img class="size-full wp-image-1655" title="iOS -like Home Screen with CoffeeScript" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/10/ios-homescreen-coffeescript.jpg" alt="iOS -like Home Screen with CoffeeScript" width="620" height="460" /></a><p class="wp-caption-text">iOS -like Home Screen with CoffeeScript</p></div>
<h3>The HTML</h3>
<p>Lets start with the HTML markup of our iOS-like home screen. As usual, this is a regular HTML5 document with stylehseets in the <em><strong>head</strong></em> and JS includes before the closing <em><strong>body</strong></em> tag.</p>
<h4>index.html</h4>
<pre class="brush:html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta charset="utf-8" /&gt;
        &lt;title&gt;iOS Home Screen with CoffeeScript | Tutorialzine Demo&lt;/title&gt;

        &lt;!-- Our CSS stylesheet file --&gt;
        &lt;link rel="stylesheet" href="assets/css/styles.css" /&gt;

        &lt;!--[if lt IE 9]&gt;
          &lt;script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt;
        &lt;![endif]--&gt;
    &lt;/head&gt;

    &lt;body&gt;

		&lt;section id="homeScreen"&gt;
			&lt;div id="mask"&gt;
				&lt;div id="allScreens"&gt;
                                   &lt;!-- The .screen divs will go here --&gt;
                                &lt;/div&gt;
			&lt;/div&gt;

			&lt;ul id="indicators"&gt;
                            &lt;!-- A LI element for every screen --&gt;
                        &lt;/ul&gt;

			&lt;div id="dock"&gt;
                            &lt;!-- The three dock icons will go here --&gt;
                        &lt;/div&gt;
		&lt;/section&gt;

        &lt;!-- JavaScript includes --&gt;
		&lt;script src="http://code.jquery.com/jquery-1.6.3.min.js"&gt;&lt;/script&gt;
		&lt;script src="assets/js/touchable.js"&gt;&lt;/script&gt;
        &lt;script src="assets/js/coffee-script.js"&gt;&lt;/script&gt;

		&lt;script type="text/coffeescript"&gt;

			# Our Code Goes Here

		&lt;/script&gt;

    &lt;/body&gt;
&lt;/html&gt;</pre>
<p>We have the <strong>#homeScreen</strong> section, which is the main container of our experiment. Inside it is the <strong>#mask</strong>, which uses <code>overflow:hidden</code> to show only one screen at the time. The <strong>#allScreens</strong> div inside it, as the name suggests, contains all the dynamically generated .screen divs with icons.</p>
<div id="attachment_1656" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/10/ios-homescreen-coffeescript/"><img class="size-full wp-image-1656" title="The #mask div shows only one screen at a time with overflow:hidden." src="http://cdn.tutorialzine.com/wp-content/uploads/2011/10/mask-screen-icons.jpg" alt="The #mask div shows only one screen at a time with overflow:hidden." width="620" height="460" /></a><p class="wp-caption-text">The #mask div shows only one screen at a time with overflow:hidden.</p></div>
<p>Following is the <strong>#indicators</strong> UL, which shows the little dots with the currently shown screen, and the <strong>#dock</strong> div.</p>
<p>As mentioned previously, CoffeeScript requires an extra compilation step, which will convert the source code to JavaScript. You can do this with the <a href="http://jashkenas.github.com/coffee-script/#installation" target="_blank">coffeescript package for node.js</a> (as explained on their website), or with <a href="https://github.com/alisey/CoffeeScript-Compiler-for-Windows" target="_blank">coffeescript.exe for windows</a>, which is standalone and ready for use executable. For small scripts, you can also include the compiler directly in your page and write your code inline in a &lt;script&gt; tag &#8211; which we will be using today.</p>
<p>At the bottom of the page, you can see our script includes. These are the <strong>jQuery library</strong>, the <strong>Touchable plugin</strong>, which will help us work with touch events, and the <strong>CoffeeScript compiler</strong> &#8211; <span style="text-decoration: underline;">coffee-script.js</span>. The compiler will look for <code>&lt;script type="text/coffeescript"&gt;</code> tags on the page, which is where we will be writing our code.</p>
<h3>The CoffeScript Code</h3>
<p>As we are writing the code inline, we do not need to compile it before deploying the web page. This is great for small web pages and during development. However, if you plan on writing larger applications, it would be a better idea to compile your code using one of the tools described above.</p>
<p>Now lets start with writing a simple class &#8211; <strong>Icon</strong>.</p>
<pre class="brush:coffeescript"># The Icon class. 

class Icon

	# The constructor. The -&gt; arrow signifies
	# a function definition.

	constructor: (@id, @title) -&gt;
		# @ is synonymous for "this". The id and title parameters
		# of the constructor are automatically added as this.id and this.title

		# @markup holds the HTML of the icon. It is
		# transformed to this.markup behind the scenes.

		@markup = "&lt;div class='icon' style='background-image:url(assets/img/icons/#{@id}.png)'
					 title='#{@title}'&gt;&lt;/div&gt;"</pre>
<p>Objects of this class are going to represent the icons in the home screen. Each icon has a <strong>markup</strong> property which contains the HTML code needed to display it. You can see that functions in CoffeeScript are defined as arrows (-&gt;), with the parameters to the function given on the left in braces. Notice that comments here start with the <strong>#</strong> symbol. You can use three <strong>###</strong> to denote multiline comments.</p>
<p>Now lets define a class for the dock icons. It will be pretty similar to the Icon class, so we are going to extend it:</p>
<pre class="brush:coffeescript"># The DockIcon class inherits from Icon

class DockIcon extends Icon
	constructor: (id, title)-&gt;

		# This calls the constructor if Icon

		super(id, title)

		# Changing the class name of the generated HTML
		@markup = @markup.replace("class='icon'","class='dockicon'")</pre>
<p>Using <code>super()</code> will call Icon&#8217;s constructor and initialize the <strong>markup</strong> property. We only need to replace the class name.</p>
<p>We will divide the home screen in individual <strong>.screen</strong> divs, each holding their own set of icons. Here is the class for that:</p>
<pre class="brush:coffeescript"># The Screen Class

class Screen

	# Function arguments can have default values
	constructor: (icons = [])-&gt;
		@icons = icons

	attachIcons: (icons = [])-&gt;
		Array.prototype.push.apply(@icons, icons)

	generate: -&gt;
		markup = []

		# Looping through the @icons array
		markup.push(icon.markup) for icon in @icons

		# The last line of every function is implicitly returned
		"&lt;div class='screen'&gt;#{markup.join('')}&lt;/div&gt;"</pre>
<p>Instead of a markup property, here we are using a <code>generate()</code> method that will return the HTML. Notice how we are looping over the array &#8211; this is called a comprehension. The part before the <strong>for</strong> keyword is executed on every element in the icons array.</p>
<div id="attachment_1654" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/10/ios-homescreen-coffeescript/"><img class="size-full wp-image-1654" title="The iOS Dock" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/10/ios-homescreen-dock.jpg" alt="The iOS Dock" width="620" height="260" /></a><p class="wp-caption-text">The iOS Dock</p></div>
<p>We now need a class that pulls everything together, and controls the transitions between the screens. Here is what it looks like:</p>
<pre class="brush:coffeescript">class Stage

	# The width of our "device" screen. This is
	# basically the width of the #mask div.

	screenWidth: 332

	constructor: (icons)-&gt;

		@currentScreen = 0
		@screens = []

		# Calculating the number of screens
		# necessary to display all the icons

		num = Math.ceil(icons.length / 9)
		i = 0

		while num--
			# we pass a slice of the icons array
			s = new Screen(icons[i...i+9])

			# adding the screen to the local screens array
			@screens.push(s)

			i+=9

	# This method populates the passed element with HTML
	addScreensTo: (element)-&gt;

                # We are using the jQuery library from within CS:
		@element = $(element)
		@element.width(@screens.length*@screenWidth)

		for screen in @screens
			@element.append(screen.generate())

	addIndicatorsTo: (elem)-&gt;

		# This method creates the small circular
		# indicators. Also using jQuery

		@ul = $(elem)

		for screen in @screens
			@ul.append('&lt;li&gt;')

		@ul.find('li:first').addClass('active');

        # ... More methods go here ...</pre>
<p>The Stage takes an array of icons in the constructor. It then calculates how many screens will be needed, and creates an object for each one, passing it a slice of the icons array.</p>
<p>We now have the markup of all these elements on the page, but we are still missing the methods that control the transition between the slides. You can see them below (still part of the Stage class):</p>
<pre class="brush:coffeescript">	goTo: (screenNum)-&gt;

		# This method animates the allScreen div in
		# order to expose the needed screen in #mask

		if @element.is(':animated')
			return false

		# if this is the first or last screen,
		# run the end of scroll animation

		if @currentScreen == screenNum

			# Parallel assignment:
			[from, to] = ['+=15','-=15']

			if @currentScreen != 0
				[from, to] = [to, from]

                        # Tell the user there aren't any more screens:
			@element.animate( { marginLeft : from }, 150 )
					.animate( { marginLeft : to }, 150 )
		else
			# If everything is ok, animate the transition between the screens.
			# The fat arrow =&gt; is a function that preserves the context of "this"

			@element.animate( { marginLeft:-screenNum*@screenWidth }, =&gt; @currentScreen = screenNum )
			@ul.find('li').removeClass('active').eq(screenNum).addClass('active');

	next: -&gt;
		toShow = @currentScreen+1

		# If there is no next screen, show
		# the last one

		if toShow == @screens.length
			toShow = @screens.length - 1

		@goTo(toShow)

	previous: -&gt;
		toShow = @currentScreen-1

		# If there is no previous screen,
		# show the first one

		if toShow == -1
			toShow = 0

		@goTo(toShow)</pre>
<p>Both the <code>next()</code> and <code>previous()</code> methods call <code>goTo()</code> internally, passing a screen number (starting from zero). The <code>goTo()</code> method animates the <strong>#allScreen</strong> div to show the needed screen.</p>
<p>All we need to do now is bind a function to the <span style="text-decoration: underline;">document.ready</span> event. For this we will use jQuery .</p>
<pre class="brush:coffeescript"># This is equivalent to $(function(){}):

$ -&gt;

        # You can skip the comma if it's on the end of a line:
	allIcons = [
		new Icon('Photos', 'Photo Gallery'), new Icon('Maps', 'Google Maps')
		new Icon('Chuzzle', 'Chuzzle'), new Icon('Safari', 'Safari')
		new Icon('Weather', 'Weather'), new Icon('nes', 'NES Emulator')
		new Icon('Calendar', 'Calendar'), new Icon('Clock', 'Clock')
		new Icon('BossPrefs', 'Boss Prefs'), new Icon('Chess', 'Chess')
		new Icon('Mail', 'Mail'), new Icon('Phone', 'Phone')
		new Icon('SMS', 'SMS Center'), new Icon('Camera', 'Camera')
		new Icon('iPod', 'iPod'), new Icon('Calculator', 'Calculator')
		new Icon('Music', 'Music'), new Icon('Poof', 'Poof')
		new Icon('Settings', 'Settings'), new Icon('YouTube', 'Youtube')
		new Icon('psx4all', 'PSx4All'), new Icon('VideoRecorder', 'Record Video')
		new Icon('Installer', 'Installer'), new Icon('Notes', 'Notes')
		new Icon('RagingThunder', 'RagingThunder'), new Icon('Stocks', 'Stocks')
		new Icon('genesis4iphone', 'Genesis'), new Icon('snes4iphone', 'SNES Emulator')
		new Icon('Calendar', 'Calendar'), new Icon('Clock', 'Clock')
		new Icon('Photos', 'Photo Gallery'), new Icon('Maps', 'Google Maps')
	]

	dockIcons = [
		new DockIcon('Camera', 'Camera')
		new DockIcon('iPod', 'iPod')
		new DockIcon('Calculator', 'Calculator')
	]

	allScreens = $('#allScreens')

	# Using the Touchable plugin to listen for
	# touch based events:

	allScreens.Touchable();

	# Creating a new stage object
	stage = new Stage(allIcons)

	stage.addScreensTo(allScreens)
	stage.addIndicatorsTo('#indicators')

	# Listening for the touchablemove event.
	# Notice the callback function. Braces on
        # function calls are optional
	allScreens.bind 'touchablemove', (e,touch)-&gt;
		stage.next() if touch.currentDelta.x &lt; -5
		stage.previous() if touch.currentDelta.x &gt; 5

	# Adding the dock icons:

	dock = $('#dock')

	for icon in dockIcons
		dock.append(icon.markup)</pre>
<p>By calling the Touchable method we are extending the element to support <a href="https://github.com/dotmaster/Touchable-jQuery-Plugin" target="_blank">several touch based events</a>. Among them is <strong>touchablemove</strong>, which is executed when the user moves his finger across the screen. It is also called when we drag with the mouse. Further down, when we bind for that event, we get a <strong>touch</strong> object as the second argument of the callback function. It holds the delta, or difference, from the beginning of the movement.</p>
<p><strong>With this our iOS-like Home Screen is complete!</strong></p>
<h3>Conclusion</h3>
<p>CoffeeScript is an interesting language that can make developing in the browser easier. You can expect to write up to 50% less code comparing to pure JavaScript.</p>
<p>But don&#8217;t fall pray to the hype surrounding it just yet &#8211; CoffeeScript isn&#8217;t going to replace JavaScript any time soon, as it sacrifices some of the agility that JS provides in attempt to make development easier. The CS way might not be the best fit for your project.</p>
<p>CoffeeScript also introduces an extra compilation step that separates you from deploying your code, but this can be solved by web frameworks that compile the code for you as is the case with Rails, where CS became a default.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/10/ios-homescreen-coffeescript/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>HTML5 File Uploads with jQuery</title>
		<link>http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/</link>
		<comments>http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/#comments</comments>
		<pubDate>Mon, 26 Sep 2011 10:48:24 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1621</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/"><img src="http://cdn.tutorialzine.com/img/featured/1621.jpg" /></a></div> Today we will be developing a small HTML5 web application that will allow people to upload photos from their computers by dragging and dropping them onto the browser window.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/"><img src="http://cdn.tutorialzine.com/img/featured/1621.jpg" /></a></div> <p>Today we will be developing a small web application called <em><strong>Upload Center</strong></em>, that will allow people to upload photos from their computers by dragging and dropping them onto the browser window, possible with the new HTML5 APIs exposed by modern browsers.</p>
<p>The photos will have a preview and a progress bar, all of which controlled on the client side. Currently, the photos are only stored in a folder on the server, but you could improve it any way you like.</p>
<h3>What are HTML5 File Uploads?</h3>
<p>Uploading files using HTML5 is actually a combination of three technologies &#8211; the new <a href="http://www.html5rocks.com/en/tutorials/file/dndfiles/" target="_blank">File Reader API</a>, the also new <a href="https://developer.mozilla.org/en/Using_files_from_web_applications" target="_blank">Drag &amp; Drop API</a>, and the good ol&#8217; AJAX (with the addition of binary data transfer). Here is a description of a HTML5 file upload process:</p>
<ol>
<li>The user drops one or more files from their file system to the browser window by dragging. Browsers that support the <em>Drag &amp; Drop API</em> will fire an event, which alongside other useful information, contains a list of files that were dropped;</li>
<li>Using the <em>File Reader API</em>, we read the files in the list as binary data, and store them in memory;</li>
<li>We use the new <strong>sendAsBinary</strong> method of the <em>XMLHttpRequest</em> object, and send the file data to the server.</li>
</ol>
<p>Sounds complicated? Yes, it could use some optimization. Fortunately, there are jQuery plugins that can do this for us. One of them is <a href="https://github.com/weixiyen/jquery-filedrop" target="_blank">Filedrop</a>, which is a wrapper around this functionality, and provides features for limiting maximum file size and specifying callback functions, which is really handy for integrating it into your web applications.</p>
<p>Currently file uploads work <strong>only in Firefox and Chrome</strong>, but upcoming major versions of the other browsers also include support for it. A simple fallback solution for older browsers would be to display a regular file input dialog, but we won&#8217;t be doing this today, as we will be focusing our attention on using HTML5.</p>
<p><strong>So lets get started!</strong></p>
<h3>The HTML</h3>
<p>The markup of our <em>Upload Center</em> couldn&#8217;t be simpler. We have a regular HTML5 document, which includes our stylesheet and<em><strong> script.js</strong></em> file, the <em>Filedrop plugin</em> and the <em>jQuery library</em>.</p>
<h4>index.html</h4>
<pre class="brush:html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta charset="utf-8" /&gt;
        &lt;title&gt;HTML5 File Drag and Drop Upload with jQuery and PHP | Tutorialzine Demo&lt;/title&gt;

        &lt;!-- Our CSS stylesheet file --&gt;
        &lt;link rel="stylesheet" href="assets/css/styles.css" /&gt;

        &lt;!--[if lt IE 9]&gt;
          &lt;script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt;
        &lt;![endif]--&gt;
    &lt;/head&gt;

    &lt;body&gt;

		&lt;header&gt;
			&lt;h1&gt;HTML5 File Upload with jQuery and PHP&lt;/h1&gt;
		&lt;/header&gt;

		&lt;div id="dropbox"&gt;
			&lt;span class="message"&gt;Drop images here to upload. &lt;br /&gt;&lt;i&gt;(they will only be visible to you)&lt;/i&gt;&lt;/span&gt;
		&lt;/div&gt;

        &lt;!-- Including The jQuery Library --&gt;
		&lt;script src="http://code.jquery.com/jquery-1.6.3.min.js"&gt;&lt;/script&gt;

		&lt;!-- Including the HTML5 Uploader plugin --&gt;
		&lt;script src="assets/js/jquery.filedrop.js"&gt;&lt;/script&gt;

		&lt;!-- The main script file --&gt;
        &lt;script src="assets/js/script.js"&gt;&lt;/script&gt;

    &lt;/body&gt;
&lt;/html&gt;</pre>
<p>The only div that the Filedrop interacts with, is <strong>#dropbox</strong>. We will pass this element to the plugin, which will detect when a file is dropped on top of it. The message span is updated if there is an error condition (for example if your browser does not support one of the HTML5 APIs that this example relies on).</p>
<div id="attachment_1627" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/09/html5-file-upload-jquery-php/"><img class="size-full wp-image-1627" title="HTML5 File Upload Center with PHP and jQuery" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/09/html5-jquery-php-upload-progress.jpg" alt="HTML5 File Upload Center with PHP and jQuery" width="620" height="300" /></a><p class="wp-caption-text">HTML5 File Upload Center with PHP and jQuery</p></div>
<p>Later, when we drop a file, our jQuery code will display a preview by adding the following markup to the page:</p>
<pre class="brush:html">&lt;div class="preview done"&gt;

	&lt;span class="imageHolder"&gt;
		&lt;img src="" /&gt;
		&lt;span class="uploaded"&gt;&lt;/span&gt;
	&lt;/span&gt;

	&lt;div class="progressHolder"&gt;
		&lt;div class="progress"&gt;&lt;/div&gt;
	&lt;/div&gt;

&lt;/div&gt;</pre>
<p>This snippet contains a preview of the image (the source attribute is going to be populated with a <a href="http://en.wikipedia.org/wiki/Data_URI_scheme" target="_blank">DataURL</a> of the picture) and a progress bar. The whole preview can have the <em>&#8220;.done&#8221;</em> class, which causes the <em>&#8220;.uploaded&#8221;</em> span to show up (it is hidden by default). This span has the green check mark as its background, and indicates the upload is complete.</p>
<p>Great, lets move on to our <em>script.js</em> file!</p>
<h3>The jQuery Code</h3>
<p>As all of the actual file transfer functionality is handled by the Filedrop plugin, we only need to call it and pass a few callbacks, so we can hook it to our <em>Upload Center</em>. We will be writing a small PHP script that handles the uploads on the server in the next section.</p>
<p>The first step is to write a helper function that takes a file object (a special object which is created by the web browser on file drop, and has properties like file name, path and size), and creates the markup for previewing the upload.</p>
<h4>assets/js/script.js</h4>
<pre class="brush:js">var template = '&lt;div class="preview"&gt;'+
						'&lt;span class="imageHolder"&gt;'+
							'&lt;img /&gt;'+
							'&lt;span class="uploaded"&gt;&lt;/span&gt;'+
						'&lt;/span&gt;'+
						'&lt;div class="progressHolder"&gt;'+
							'&lt;div class="progress"&gt;&lt;/div&gt;'+
						'&lt;/div&gt;'+
					'&lt;/div&gt;'; 

	function createImage(file){

		var preview = $(template),
			image = $('img', preview);

		var reader = new FileReader();

		image.width = 100;
		image.height = 100;

		reader.onload = function(e){

			// e.target.result holds the DataURL which
			// can be used as a source of the image:

			image.attr('src',e.target.result);
		};

		// Reading the file as a DataURL. When finished,
		// this will trigger the onload function above:
		reader.readAsDataURL(file);

		message.hide();
		preview.appendTo(dropbox);

		// Associating a preview container
		// with the file, using jQuery's $.data():

		$.data(file,preview);
	}</pre>
<p>The <em><strong>template</strong></em> variable holds the HTML5 markup of the preview. We get the DataURL of the image (a base64 encoded representation of the image bytes) and add it as the source of the image. Everything is then appended to the dropbox container. Now we are left with calling the filedrop plugin:</p>
<h4>assets/js/script.js</h4>
<pre class="brush:js">$(function(){

	var dropbox = $('#dropbox'),
		message = $('.message', dropbox);

	dropbox.filedrop({
		// The name of the $_FILES entry:
		paramname:'pic',

		maxfiles: 5,
    	maxfilesize: 2, // in mb
		url: 'post_file.php',

		uploadFinished:function(i,file,response){
			$.data(file).addClass('done');
			// response is the JSON object that post_file.php returns
		},

    	error: function(err, file) {
			switch(err) {
				case 'BrowserNotSupported':
					showMessage('Your browser does not support HTML5 file uploads!');
					break;
				case 'TooManyFiles':
					alert('Too many files! Please select 5 at most!');
					break;
				case 'FileTooLarge':
					alert(file.name+' is too large! Please upload files up to 2mb.');
					break;
				default:
					break;
			}
		},

		// Called before each upload is started
		beforeEach: function(file){
			if(!file.type.match(/^image\//)){
				alert('Only images are allowed!');

				// Returning false will cause the
				// file to be rejected
				return false;
			}
		},

		uploadStarted:function(i, file, len){
			createImage(file);
		},

		progressUpdated: function(i, file, progress) {
			$.data(file).find('.progress').width(progress);
		}

	});

	var template = '...'; 

	function createImage(file){
		// ... see above ...
	}

	function showMessage(msg){
		message.html(msg);
	}

});</pre>
<p>With this, every valid image file that is dropped on the <em><strong>#dropbox</strong></em> div gets uploaded to <strong>post_file.php</strong>, which you can see in the next section.</p>
<div id="attachment_1628" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/09/html5-file-upload-jquery-php/"><img class="size-full wp-image-1628" title="Upload Complete!" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/09/html5-jquery-php-upload-done.jpg" alt="Upload Complete!" width="620" height="300" /></a><p class="wp-caption-text">Upload Complete!</p></div>
<h3>The PHP Code</h3>
<p>On the PHP side of things, there is no difference between a regular form file upload and a drag and drop one. This means that you can easily provide a fallback solution to your application and reuse the same backend.</p>
<h4>post_file.php</h4>
<pre class="brush:php">// If you want to ignore the uploaded files,
// set $demo_mode to true;

$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');

if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
	exit_status('Error! Wrong HTTP method!');
}

if(array_key_exists('pic',$_FILES) &amp;&amp; $_FILES['pic']['error'] == 0 ){

	$pic = $_FILES['pic'];

	if(!in_array(get_extension($pic['name']),$allowed_ext)){
		exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
	}	

	if($demo_mode){

		// File uploads are ignored. We only log them.

		$line = implode('		', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
		file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);

		exit_status('Uploads are ignored in demo mode.');
	}

	// Move the uploaded file from the temporary
	// directory to the uploads folder:

	if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
		exit_status('File was uploaded successfuly!');
	}

}

exit_status('Something went wrong with your upload!');

// Helper functions

function exit_status($str){
	echo json_encode(array('status'=&gt;$str));
	exit;
}

function get_extension($file_name){
	$ext = explode('.', $file_name);
	$ext = array_pop($ext);
	return strtolower($ext);
}</pre>
<p>The script runs some checks on the HTTP method that was used to request the page and the validity of the file extension. Demo mode is mainly for <em>demo.tutorialzine.com</em>, where I don&#8217;t want to store any file uploads (if you don&#8217;t call <em>move_uploaded_file</em> in your script, the file is deleted automatically at the end of the request).</p>
<p>Now lets make it pretty!</p>
<h3>The CSS Styles</h3>
<p>I left out the parts of the stylesheet that are not directly related to the uploads. You can see everything in <em><strong>styles.css</strong></em>.</p>
<h4>assets/css/styles.css</h4>
<pre class="brush:css">/*-------------------------
	Dropbox Element
--------------------------*/

#dropbox{
	background:url('../img/background_tile_3.jpg');

	border-radius:3px;
	position: relative;
	margin:80px auto 90px;
	min-height: 290px;
	overflow: hidden;
	padding-bottom: 40px;
    width: 990px;

	box-shadow:0 0 4px rgba(0,0,0,0.3) inset,0 -3px 2px rgba(0,0,0,0.1);
}

#dropbox .message{
	font-size: 11px;
    text-align: center;
    padding-top:160px;
    display: block;
}

#dropbox .message i{
	color:#ccc;
	font-size:10px;
}

#dropbox:before{
	border-radius:3px 3px 0 0;
}

/*-------------------------
	Image Previews
--------------------------*/

#dropbox .preview{
	width:245px;
	height: 215px;
	float:left;
	margin: 55px 0 0 60px;
	position: relative;
	text-align: center;
}

#dropbox .preview img{
	max-width: 240px;
	max-height:180px;
	border:3px solid #fff;
	display: block;

	box-shadow:0 0 2px #000;
}

#dropbox .imageHolder{
	display: inline-block;
	position:relative;
}

#dropbox .uploaded{
	position: absolute;
	top:0;
	left:0;
	height:100%;
	width:100%;
	background: url('../img/done.png') no-repeat center center rgba(255,255,255,0.5);
	display: none;
}

#dropbox .preview.done .uploaded{
	display: block;
}

/*-------------------------
	Progress Bars
--------------------------*/

#dropbox .progressHolder{
	position: absolute;
	background-color:#252f38;
	height:12px;
	width:100%;
	left:0;
	bottom: 0;

	box-shadow:0 0 2px #000;
}

#dropbox .progress{
	background-color:#2586d0;
	position: absolute;
	height:100%;
	left:0;
	width:0;

	box-shadow: 0 0 1px rgba(255, 255, 255, 0.4) inset;

	-moz-transition:0.25s;
	-webkit-transition:0.25s;
	-o-transition:0.25s;
	transition:0.25s;
}

#dropbox .preview.done .progress{
	width:100% !important;
}</pre>
<p>The <em>.progress</em> div is positioned absolutely. Changing its width (in percent) makes for a natural progress indicator. Throw in a 0.25 transition, and you have animated increments which would be a bit tricky to do with jQuery alone.</p>
<p><strong>With this our HTML5 Upload Center is complete!</strong></p>
<h3>We&#8217;re done!</h3>
<p>You can use this as a starting point for a file upload service, HTML5 gallery, file manager or your app&#8217;s new admin panel. Add your thoughts or suggestions in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/feed/</wfw:commentRss>
		<slash:comments>61</slash:comments>
		</item>
		<item>
		<title>Display your Favorite Tweets using PHP and jQuery</title>
		<link>http://tutorialzine.com/2011/08/display-favorite-tweets-php-css/</link>
		<comments>http://tutorialzine.com/2011/08/display-favorite-tweets-php-css/#comments</comments>
		<pubDate>Fri, 05 Aug 2011 14:22:01 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1559</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2011/08/display-favorite-tweets-php-css/"><img src="http://cdn.tutorialzine.com/img/featured/1559.jpg" /></a></div> In this tutorial, we will be writing a PHP class that will fetch, cache, and display your favorite tweets in a beautiful CSS3 interface.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2011/08/display-favorite-tweets-php-css/"><img src="http://cdn.tutorialzine.com/img/featured/1559.jpg" /></a></div> <p>If you have a twitter account, you oftentimes find yourself looking for a way to display your latest tweets on your website or blog. This is pretty much a solved problem. There are jQuery plugins, PHP classes and <a href="http://tutorialzine.com/2009/10/jquery-twitter-ticker/" target="_blank">tutorials</a> that show you how to do this.</p>
<p>However, what happens if you only want to display certain tweets, that you have explicitly marked to show? As minimalistic twitter&#8217;s feature set is, it does provide a solution to this problem &#8211; favorites.</p>
<p>In this tutorial, we will be writing a PHP class that will fetch, cache, and display your favorite tweets in a beautiful CSS3 interface.</p>
<h3>HTML</h3>
<p>You can see the markup of the page that we will be using as a foundation below. The <strong>#container</strong> div will hold the tweets (which we will be generating in the PHP section of the tutorial).</p>
<h4>index.php</h4>
<pre class="brush:html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta charset="utf-8" /&gt;
        &lt;title&gt;Display your Favorite Tweets using PHP and jQuery | Tutorialzine Demo&lt;/title&gt;

        &lt;!-- Our CSS stylesheet file --&gt;
        &lt;link rel="stylesheet" href="assets/css/styles.css" /&gt;

        &lt;!--[if lt IE 9]&gt;
          &lt;script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt;
        &lt;![endif]--&gt;
    &lt;/head&gt;

    &lt;body&gt;

		&lt;div id="container"&gt;
	        &lt;!-- The tweets will go here --&gt;
        &lt;/div&gt;

        &lt;!-- JavaScript includes --&gt;
		&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"&gt;&lt;/script&gt;
        &lt;script src="assets/js/jquery.splitlines.js"&gt;&lt;/script&gt;
        &lt;script src="assets/js/script.js"&gt;&lt;/script&gt;

    &lt;/body&gt;
&lt;/html&gt;</pre>
<p>We will be using the <a href="http://42pixels.com/demos/splitlines/demos.html" target="_blank">splitLines plugin</a>, which as its name suggest, will split the tweets into separate divs, one for each line of text. This is necessary as it is the only we can apply padding to the lines individually (as an illustration, view the demo with JS disabled). However, the demo will still keep most of its design without it.</p>
<p>As for the generation of the tweets, we will be creating a PHP class that will handle it for us. We will only need to call its generate method inside the <strong>#container</strong> div like this: <code>$tweets-&gt;generate(5)</code>, which will show the 5 most recent liked tweets. This method will output an unordered list with tweets:</p>
<h4>Tweet markup</h4>
<pre class="brush:html">&lt;ul class="tweetFavList"&gt;
&lt;li&gt;
	&lt;p&gt;The text of the tweet goes here&lt;/p&gt;
	&lt;div class="info"&gt;
		&lt;a title="Go to Tutorialzine's twitter page" class="user"
			href="http://twitter.com/Tutorialzine"&gt;Tutorialzine&lt;/a&gt;

		&lt;span title="Retweet Count" class="retweet"&gt;19&lt;/span&gt;

		&lt;a title="Shared 3 days ago" target="_blank" class="date"
			href="http://twitter.com/Tutorialzine/status/98439169621241856"&gt;3 days ago&lt;/a&gt;
	&lt;/div&gt;

	&lt;div class="divider"&gt;&lt;/div&gt;

&lt;/li&gt;

&lt;!-- More tweets here .. --&gt;

&lt;/ul&gt;</pre>
<p>The text of the tweet will be held in a paragraph, with additional information available in the <strong>.info</strong> div. Now lets write the PHP class.</p>
<div id="attachment_1564" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/08/display-favorite-tweets-php-css/"><img class="size-full wp-image-1564" title="Display Your Favorite Tweets with jQuery and PHP" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/08/display-favorite-tweets-php-jquery-css.jpg" alt="Display Your Favorite Tweets with jQuery and PHP" width="620" height="460" /></a><p class="wp-caption-text">Display Your Favorite Tweets with jQuery and PHP</p></div>
<h3>PHP</h3>
<p>We will name our class <strong><em>FavoriteTweetsList</em></strong>. It will take a twitter username as a parameter, and expose a number of useful methods for fetching tweets and generating HTML markup.</p>
<p>The class will fetch the favorite tweets json feed, located at <em>http://api.twitter.com/1/favorites/<strong>USERNAME</strong>.json</em> (see <a href="http://api.twitter.com/1/favorites/Tutorialzine.json">Tutorialzine&#8217;s feed</a> as an example). Additionally, it will include caching, so that a request is made only once every three hours, which will speed things up.</p>
<h4>FavoriteTweetsList.class.php</h4>
<pre class="brush:php">class FavoriteTweetsList{
	private $username;
	const cache = "cache_tweets.ser";

	public function __construct($username){
		$this-&gt;username = $username;
	}

	/* The get method returns an array of tweet objects */

	public function get(){

		$cache = self::cache;
		$tweets = array();

		if(file_exists($cache) &amp;&amp; time() - filemtime($cache) &lt; 3*60*60){

			// Use the cache if it exists and is less than three hours old
			$tweets = unserialize(file_get_contents($cache));
		}
		else{

			// Otherwise rebuild it
			$tweets = json_decode($this-&gt;fetch_feed());
			file_put_contents($cache,serialize($tweets));
		}

		if(!$tweets){
			$tweets = array();
		}

		return $tweets;
	}

	/* The generate method takes an array of tweets and build the markup */

	public function generate($limit=10, $className = 'tweetFavList'){

		echo "&lt;ul class='$className'&gt;";

		// Limiting the number of shown tweets
		$tweets = array_slice($this-&gt;get(),0,$limit);

		foreach($tweets as $t){

			$id			= $t-&gt;id_str;
			$text		= self::formatTweet($t-&gt;text);
			$time		= self::relativeTime($t-&gt;created_at);
			$username	= $t-&gt;user-&gt;screen_name;
			$retweets	= $t-&gt;retweet_count;

			?&gt;

			&lt;li&gt;
				&lt;p&gt;&lt;?php echo $text ?&gt;&lt;/p&gt;
				&lt;div class="info"&gt;
					&lt;a href="http://twitter.com/&lt;?php echo $username ?&gt;" class="user"
						title="Go to &lt;?php echo $username?&gt;'s twitter page"&gt;
                    	                    	&lt;?php echo $username ?&gt;&lt;/a&gt;

					&lt;?php if($retweets &gt; 0):?&gt;
						&lt;span class="retweet" title="Retweet Count"&gt;
                    	                    	&lt;?php echo $retweets ?&gt;&lt;/span&gt;
					&lt;?php endif;?&gt;

					&lt;a href="http://twitter.com/&lt;?php echo $username,'/status/',$id?&gt;"
                    	class="date" target="_blank" title="Shared &lt;?php echo $time?&gt;"&gt;
                    	&lt;?php echo $time?&gt;&lt;/a&gt;
				&lt;/div&gt;

                &lt;div class="divider"&gt;&lt;/div&gt;

            &lt;/li&gt;

            &lt;?php
		}

		echo "&lt;/ul&gt;";
	}

	/* Helper methods and static functions */

	private function fetch_feed(){
		return file_get_contents("http://api.twitter.com/1/favorites/{$this-&gt;username}.json");
	}

	private static function relativeTime($time){

		$divisions	= array(1,60,60,24,7,4.34,12);
		$names		= array('second','minute','hour','day','week','month','year');
		$time		= time() - strtotime($time);

		$name = "";

		if($time &lt; 10){
			return "just now";
		}

		for($i=0; $i&lt;count($divisions); $i++){
			if($time &lt; $divisions[$i]) break;

			$time = $time/$divisions[$i];
			$name = $names[$i];
		}

		$time = round($time);

		if($time != 1){
			$name.= 's';
		}

		return "$time $name ago";
	}

	private static function formatTweet($str){

		// Linkifying URLs, mentionds and topics. Notice that
		// each resultant anchor type has a unique class name.

		$str = preg_replace(
			'/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/i',
			'&lt;a class="link" href="$1" target="_blank"&gt;$1&lt;/a&gt;',
			$str
		);

		$str = preg_replace(
			'/(\s|^)@([\w\-]+)/',
			'$1&lt;a class="mention" href="http://twitter.com/#!/$2" target="_blank"&gt;@$2&lt;/a&gt;',
			$str
		);

		$str = preg_replace(
			'/(\s|^)#([\w\-]+)/',
			'$1&lt;a class="hash" href="http://twitter.com/search?q=%23$2"&gt;#$2&lt;/a&gt;',
			$str
		);

		return $str;
	}
}</pre>
<p>Of the methods above, <code>generate()</code> is the one that you will most likely be working with directly. It takes the number of tweets to be displayed, and an optional <strong>class</strong> parameter, that overrides the default class attribute of the unordered list.</p>
<p>Now that we have the <strong>FavoriteTweetsList</strong> class in place, we simply need to instantiate an object, passing it a twitter username, like this:</p>
<h4>index.php</h4>
<pre class="brush:php">require "includes/FavoriteTweetsList.class.php";

$tweets = new FavoriteTweetsList('Tutorialzine');</pre>
<p>Calling the <code>$tweets-&gt;generate()</code> will show that user&#8217;s latest faved tweets.</p>
<h3>jQuery</h3>
<p>As we are using the <em>splitLines</em> jQuery plugin, we already have most of the work done for us. We simply have to loop through the paragraph elements holding the text of the tweets, and call the plugin.</p>
<h4>script.js</h4>
<pre class="brush:js">$(function(){
	var width = $('ul.tweetFavList p').outerWidth();

	// Looping through the p elements
	// and calling the splitLines plugin

	$('ul.tweetFavList p').each(function(){
		$(this).addClass('sliced').splitLines({width:width});
	});
});</pre>
<p>This will split the contents of the paragraph into lines, each held in an individual div, which we can style.</p>
<h3>CSS</h3>
<p>First lets style the unordered list and the paragraph elements.</p>
<h4>styles.css &#8211; 1</h4>
<pre class="brush:css">ul.tweetFavList{
	margin:0 auto;
	width:600px;
	list-style:none;
}

ul.tweetFavList p{
	background-color: #363636;
	color: #FFFFFF;
	display: inline;
	font-size: 28px;
	line-height: 2.25;
	padding: 10px;
}

/* Coloring the links differently */

ul.tweetFavList a.link		{ color:#aed080;}
ul.tweetFavList a.mention	{ color:#6fc6d9;}
ul.tweetFavList a.hash		{ color:#dd90e9;}</pre>
<p>If you take a closer look at the <strong>formatTweet()</strong> static method in the PHP class, you will see that we are adding a class name for each type of hyperlink &#8211; a regular link, a mention or a hash, so we can style them differently.</p>
<p>When the page loads, jQuery adds <strong><em>sliced</em></strong> as a class to each paragraph. This class undoes some of the styling applied to the paragraphs by default as a fallback, so we can display the individual lines properly.</p>
<h4>styles.css &#8211; 2</h4>
<pre class="brush:css">/* The sliced class is assigned by jQuery */

ul.tweetFavList p.sliced{
	background:none;
	display:block;
	padding:0;
	line-height:2;
}

/* Each div is a line generated by the splitLines plugin */

ul.tweetFavList li p div{
	background-color: #363636;
	box-shadow: 2px 2px 2px rgba(33, 33, 33, 0.5);
	display: inline-block;
	margin-bottom: 6px;
	padding: 0 10px;
	white-space: nowrap;
}</pre>
<p>Next we will style the colorful information boxes that hold the <em>author username</em>, <em>publish date</em> and <em>retweet count</em>.</p>
<h4>styles.css &#8211; 3</h4>
<pre class="brush:css">ul.tweetFavList .info{
	overflow: hidden;
	padding: 15px 0 5px;
}

/* The colorful info boxes */

ul.tweetFavList .user,
ul.tweetFavList .retweet,
ul.tweetFavList .date{
	float:left;
	padding:4px 8px;
	color:#fff !important;
	text-decoration:none;
	font-size:11px;
	box-shadow: 1px 1px 1px rgba(33, 33, 33, 0.3);
}

ul.tweetFavList .user{
	background-color:#6fc6d9;
}

ul.tweetFavList .retweet{
	background-color:#dd90e9;
	cursor:default;
}

ul.tweetFavList .date{
	background-color:#aed080;
}</pre>
<p>And finally we will style the divider. This is a single div, but thanks to <code>:before</code>/<code>:after</code> pseudo elements, we add two more circles to the left and to the right of it.</p>
<h4>styles.css &#8211; 4</h4>
<pre class="brush:css">/* Styling the dotted divider */

ul.tweetFavList .divider,
ul.tweetFavList .divider:before,
ul.tweetFavList .divider:after{
	background-color: #777777;
	border-radius: 50% 50% 50% 50%;
	height: 12px;
	margin: 60px auto 80px;
	width: 12px;
	position:relative;
	box-shadow: 1px 1px 0 rgba(255, 255, 255, 0.5);
}

ul.tweetFavList .divider:before,
ul.tweetFavList .divider:after{
	margin:0;
	position:absolute;
	content:'';
	top:0;
	left:-40px;
}

ul.tweetFavList .divider:after{
	left:auto;
	right:-40px;
}

ul.tweetFavList li:last-child .divider{
	display:none;
}</pre>
<p>With this our favorited tweet list is complete!</p>
<h3>Done</h3>
<p>This example can be used to build a simple testimonials section, or to highlight tweets that you think your readers would find worthy. You can even see it implemented on the sidebar of this very site.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/08/display-favorite-tweets-php-css/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Bubble Slideshow Effect with jQuery</title>
		<link>http://tutorialzine.com/2011/07/bubble-slideshow-jquery-css/</link>
		<comments>http://tutorialzine.com/2011/07/bubble-slideshow-jquery-css/#comments</comments>
		<pubDate>Thu, 28 Jul 2011 19:41:06 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1551</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2011/07/bubble-slideshow-jquery-css/"><img src="http://cdn.tutorialzine.com/img/featured/1551.jpg" /></a></div> Today we will be building a jQuery-powered bubble animation effect. It will be a great way to present a set of images on your website as a interesting slideshow.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2011/07/bubble-slideshow-jquery-css/"><img src="http://cdn.tutorialzine.com/img/featured/1551.jpg" /></a></div> <p>Today we will be building a jQuery-powered bubble animation effect. It will be a great way to present a set of images on your website as a interesting slideshow. And as the code will be completely modular, you will be able to easily use it and modify it.</p>
<h3>The HTML</h3>
<p>The slideshow effect we will be creating today, will take the form of an easy to use jQuery plugin. As most of the work is done by the plugin, there isn&#8217;t much to do in this section. However, to use the plugin you need to add an unordered list on your page. The individual slides of the slideshow will be added as LI elements.</p>
<h4>index.html</h4>
<pre class="brush:html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta charset="utf-8" /&gt;
        &lt;title&gt;Bubble Slideshow Effect with jQuery | Tutorialzine Demo&lt;/title&gt;

        &lt;!-- Our CSS stylesheet file --&gt;
        &lt;link rel="stylesheet" href="assets/css/styles.css" /&gt;

        &lt;!-- The plugin stylehseet --&gt;
        &lt;link rel="stylesheet" href="assets/jquery.bubbleSlideshow/jquery.bubbleSlideshow.css" /&gt;

        &lt;!--[if lt IE 9]&gt;
          &lt;script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt;
        &lt;![endif]--&gt;
    &lt;/head&gt;

    &lt;body&gt;

        &lt;!-- The bubble slideshow holder --&gt;
		&lt;ul id="slideShow"&gt;&lt;/ul&gt;

		&lt;!-- JavaScript includes --&gt;
		&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"&gt;&lt;/script&gt;
        &lt;script src="assets/jquery.bubbleSlideshow/bgpos.js"&gt;&lt;/script&gt;
        &lt;script src="assets/jquery.bubbleSlideshow/jquery.bubbleSlideshow.js"&gt;&lt;/script&gt;
        &lt;script src="assets/js/script.js"&gt;&lt;/script&gt;

    &lt;/body&gt;
&lt;/html&gt;</pre>
<p>To be able to use the plugin, you will need to include <em>jquery.bubbleSlideshow.css</em> in the head of the page, <em>bgpos.js</em> and <em>jquery.bubbleSlideshow.js</em> before the closing body tag. <a href="https://github.com/brandonaaron/jquery-cssHooks" target="_blank">bgpos.js</a> is a jQuery CSS hooks plugin that will allow us to animate the <em>background-position</em> property (needed in the bubble animation), and <em>jquery.bubbleSlideshow.js</em> holds the code we will be writing today.  Also remember to include the jQuery library as well.</p>
<p>You can see a simple explanation of the bubble effect below.</p>
<div id="attachment_1555" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/07/bubble-slideshow-jquery-css/"><img class="size-full wp-image-1555" title="The Bubble Effect Explained" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/07/the-bubble-effect-explained.jpg" alt="The Bubble Effect Explained" width="620" height="460" /></a><p class="wp-caption-text">The Bubble Effect Explained</p></div>
<h3>JavaScript and jQuery</h3>
<p>First we will write a JavaScript class named <em>Bubble</em>. Every bubble in the slideshow is going to be an object of this class. It will have properties such as <strong>top</strong> and <strong>left</strong> (position offsets), <strong>size</strong> (diameter of the circle) and an <strong>elem</strong> property, which is a jQuery object containing the actual div. We will use this property later when we animate the bubble in the <code>flyFrom()</code> method.</p>
<h4>jquery.bubbleSlideshow.js</h4>
<pre class="brush:js">	// This is the Bubble class. It takes left and top
	// coordinates, size (diameter) and a image URL

	function Bubble( left, top, size, imgURL ){

		this.top	= top;
		this.left	= left;
		this.size	= size;

		// This places the center of the
		// circles on the specified position:

		top -= size/2;
		left-= size/2;

		this.elem = $('&lt;div&gt;',{
			'class':'bubble',
			'css'	: {
				'width'		: size,
				'height'	: size,
				'top'		: top,
				'left'		: left,
				'background-position': (-left)+'px '+(-top)+'px',
				'background-image': 'url('+imgURL+')'
			}
		});

	}

	// The fly from method takes a starting position, time,
	// and a callback function, executed when the animation finishes.

	Bubble.prototype.flyFrom = function( startX, startY, time, callBack ){

		time = time || 250;
		callBack = callBack || function(){};

		startX -= this.size/2;
		startY -= this.size/2;

		// Offsetting the element

		this.elem.css({
			'display'				: 'block',
			'backgroundPositionX'	: -startX,
			'backgroundPositionY'	: -startY,
			'left'					: startX,
			'top'					: startY
		});

		// Animating it to where it should be

		this.elem.animate({
			'backgroundPositionX'	: -this.left,
			'backgroundPositionY'	: -this.top,
			'left'					: this.left,
			'top'					: this.top
		}, time, 'easeOutCirc', callBack );

	};

	// Helper function for generating random
	// values in the [min,max] range

	function rand( min, max ){
		return Math.floor( Math.random()*((max+1)-min) + min);
	}</pre>
<p>The <code>flyFrom()</code> method takes a set of coordinates, that determine the position the bubble <strong>flies in from</strong>. It still ends up in the position that you specify when creating it. This method is defined on the Bubble function&#8217;s prototype, which automatically makes it available to all its instances. This is a more effective approach, as only one copy of this method exists at a time, instead of a copy of this method for each object. Also, notice the <code>rand()</code> function defined at the bottom of the fragment. It mimics the PHP function of the same name and is used throughout the plugin code.</p>
<p>Now that we have the class in place, lets write a function that creates an array with bubble objects, appends them to a new LI element, and animates them. The function takes three parameters:</p>
<ul>
<li><strong>stage</strong>, which is a jQuery object that holds a UL element. This will hold the slideshow, with each slide being an individual LI;</li>
<li><strong>imgURL</strong> is the URL of the image that will be shown in the bubbles;</li>
<li><strong>func</strong> is a callback function that will be called once all bubble animations are complete. This is used to switch the slides and destroy the bubbles, as they will not be needed after the transition to the new slide is complete;</li>
</ul>
<p>As you guessed, for every slide transition, a new random set of bubbles is created, and destroyed after the next slide is made visible.</p>
<div id="attachment_1556" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/07/bubble-slideshow-jquery-css/"><img class="size-full wp-image-1556" title="Bubble Slideshow Effect" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/07/bubble-effect-jquery-css.jpg" alt="Bubble Slideshow Effect" width="620" height="460" /></a><p class="wp-caption-text">Bubble Slideshow Effect</p></div>
<h4>jquery.bubbleSlideshow.js</h4>
<pre class="brush:js">	function showBubbles( stage, imgURL, func ){

		// This function appends a new LI element to the UL
		// and uses it to hold and animate the bubbles.

		var i = 0,
			bubbles = [],
			totalBubbles = 75,
			stageWidth = stage.outerWidth(),
			stageHeight = stage.outerHeight(),
			emptyFunc = function(){};

		// This li holds the bubbles
		var li = $('&lt;li class="bubbleStage"&gt;').appendTo(stage);

		// This function is passed to the flyFrom method call:

		var callBack = function(){

			// Waiting for the func function to
			// finish and removing the li.

			$.when(func()).then(function(){
				li.remove();
			});
		};

		for( i=0; i&lt;totalBubbles; i++ ){

			var x	 = rand(0, stageWidth),
				y	 = rand(0,stageHeight),
				size = rand(30,150);

			var bubble = new Bubble( x, y, size, imgURL );
			li.append(bubble.elem);

			bubbles.push(bubble);
		}

		// Sorting the bubbles so that the
		// bubbles closest to the top border of
		// the image come first:

		bubbles = bubbles.sort(function( b1, b2 ){
			return b1.top+b1.size/2 &gt; b2.top+b2.size/2;
		});

		// Looping through all the bubbles,
		// and triggering their flyFrom methods

		for( i=0; i&lt;bubbles.length; i++){

			(function( bubble, i ){
				setTimeout(function(){

					bubble.flyFrom(
						stageWidth/2,
						stageHeight+200,
						250,
						(i == bubbles.length-1) ? callBack : emptyFunc
					);

				// This Math.floor schedules five bubbles
				// to be animated simultaneously

				}, Math.floor(i/5)*100); 

			})( bubbles[i], i );
		}
	}</pre>
<p>Great! So now we have a function that creates a set of bubbles in a new LI element and animates them. But these are only functions, they are not a plugin yet, so we will have to work on that. Also we are still missing the slides themselves. Lets write the missing pieces:</p>
<h4>jquery.bubbleSlideshow.js</h4>
<pre class="brush:js">$.fn.bubbleSlideshow = function(photos){

		if(!$.isArray(photos)){
			throw new Error("You need to pass an array of photo URLs as a parameter!");
		}

		photos = photos.reverse();

		var ul = this.addClass('bubbleSlideshow');

		$.each(photos,function(){
			ul.append('&lt;li&gt;&lt;img src="'+this+'" /&gt;&lt;/li&gt;');
		});

		// These methods are available externally and
		// can be used to control the bubble slideshow

		ul.showNext = function(){
			showNext(ul);
		};

		ul.showPrev = function(){
			showPrev(ul);
		};

		ul.autoAdvance = function(timeout){
			timeout = timeout || 6000;
			autoAdvance(ul,timeout);
		};

		ul.stopAutoAdvance = function(){
			stopAutoAdvance(ul);
		};

		return ul;
	};</pre>
<p>The code above defines a new plugin called <code>bubbleSlideshow()</code>. It should be called on a UL element and takes an array of photo URLs as its parameter. These are added to the UL.</p>
<p>Inside its body, the plugin creates a new LI element for each of the photos in the array, and adds <strong>showNext</strong>, <strong>showPrev</strong>, <strong>autoAdvance</strong> and <strong>stopAutoAdvance</strong> methods to the UL. These wrap around local functions with the same names, which you can see below:</p>
<h4>jquery.bubbleSlideshow.js</h4>
<pre class="brush:js">	function autoAdvance(stage,timeout){
		stage.data('timeout',setTimeout(function(){
			showNext(stage);
			autoAdvance(stage,timeout);
		},timeout));
	}

	function stopAutoAdvance(stage){
		clearTimeout(stage.data('timeout'));
	}

	function showNext(stage){
		showFrame(stage, stage.find('li.bubbleImageFrame').first());
	}

	function showPrev(stage){
		showFrame(stage, stage.find('li.bubbleImageFrame').last().prev());
	}

	function showFrame(stage, frame ){

		// This function shows a frame,
		// passed as a jQuery object

		if(stage.data('working')){
			// Prevents starting more than
			// one animation at a time:
			return false;
		}
		stage.data('working',true);

		var frame = frame.hide().detach();

		// Using the showBubbles function, defined below.
		// The frame is showed after the bubble animation is over.

		showBubbles( stage, frame.find('img').attr('src'), function(){
			stage.append(frame);
			stage.data('working',false);

			// This returns a jQuery Promise object.
			return frame.fadeIn('slow');
		});		

	}</pre>
<p>I used <em>&#8220;local&#8221;</em> to describe these functions, because they are not available from outside the plugin. The <strong>showNext</strong> and <strong>showPrev </strong>functions above both call <strong>showFrame</strong>, passing it the UL and the LI slide that is to be shown. <strong>showFrame </strong>makes sure that there is only one animation running at a time, and calls the <strong>showBubbles </strong>function we already wrote.</p>
<p>The callback function that is passed along with the method call, displays the slide you want to show above all the others by appending it last in the UL (the slides are absolutely positioned, which means that the last element in the UL is shown on top). This function is called once the bubble animation completes.</p>
<p>Here is how you initialize the bubble slideshow:</p>
<h4>script.js</h4>
<pre class="brush:js">$(function(){
	var photos = [
		'http://farm6.static.flickr.com/5230/5822520546_dd2b6d7e24_z.jpg',
		'http://farm5.static.flickr.com/4014/4341260799_b466a1dfe4_z.jpg',
		'http://farm6.static.flickr.com/5138/5542165153_86e782382e_z.jpg',
		'http://farm5.static.flickr.com/4040/4305139726_829be74e29_z.jpg',
		'http://farm4.static.flickr.com/3071/5713923079_60f53b383f_z.jpg',
		'http://farm5.static.flickr.com/4108/5047301420_621d8a7912_z.jpg'
	];

	var slideshow = $('#slideShow').bubbleSlideshow(photos);

	$(window).load(function(){
		slideshow.autoAdvance(5000);
	});

	// Other valid method calls:

	// slideshow.showNext();
	// slideshow.showPrev();
	// slideshow.stopAutoAdvance();
});</pre>
<p>All that is left is to define a few CSS rules that add properties such positioning, overflows and background-positions:</p>
<h4>jquery.bubbleSlideshow.css</h4>
<pre class="brush:css">ul.bubbleSlideshow{
	position:relative;
	list-style:none;
	overflow:hidden;
}

.bubbleSlideshow li{
	position:absolute;
	top:0;
	left:0;
}

.bubbleSlideshow li img{
	display:block;
}

.bubbleSlideshow li div.bubble{
	-moz-border-radius:50%;
	-webkit-border-raidus:50%;
	border-radius:50%;

	background-repeat:no-repeat;
	display:none;
	position:absolute;
}</pre>
<p><strong>With this the bubble effect slideshow is complete!</strong></p>
<h3>Final words</h3>
<p>The effect we made today may not be limited only to slideshows. It can be used to build unique website backgrounds, headers and presentations. The plugin is built to automatically resize to fit the UL, so you can easily change its size by tweaking a few CSS properties.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/07/bubble-slideshow-jquery-css/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Having Fun With CSS3: Spinning Newspapers</title>
		<link>http://tutorialzine.com/2011/07/spinning-newspaper-effect-css3/</link>
		<comments>http://tutorialzine.com/2011/07/spinning-newspaper-effect-css3/#comments</comments>
		<pubDate>Thu, 21 Jul 2011 18:11:40 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1543</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2011/07/spinning-newspaper-effect-css3/"><img src="http://cdn.tutorialzine.com/img/featured/1543.jpg" /></a></div> Lets have some fun today, and build the classical "spinning newspaper" scene using CSS3 animations, jQuery, and the canvas element, picking useful techniques along the way.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2011/07/spinning-newspaper-effect-css3/"><img src="http://cdn.tutorialzine.com/img/featured/1543.jpg" /></a></div> <p>Imagine a cop drama taking place in the 1930s. After a streak of bank heists, a young detective is given the case of his life. He accepts the challenge, and after grueling months of hard work and life-threatening situations, he manages to bring the bad guys to justice.</p>
<p>What follows is a classical device used by film makers of the period &#8211; newspapers flashing and spinning towards the camera, praising the heroic feats of our protagonist.</p>
<p>So lets have some fun and build this classical scene using the CSS3 animations capabilities of the new versions of Firefox, Chrome and Safari, picking useful techniques along the way.</p>
<h3>The Idea</h3>
<p>Using JavaScript, we will load a sliced up version of the newspaper (slices are independently encoded as PNG or JPG for smaller filesize), and combine them in a single canvas element. We will also load a custom font from <a href="https://developer.mozilla.org/en/CSS/CSS_animations" target="_blank">Google WebFonts</a>, which we use to write the article title to the canvas.</p>
<p>We also define a simple CSS3 keyframe animation, which uses transformations such as <code>scale()</code> and <code>rotate()</code> to animate the canvas elements. Appending the canvas to the page triggers the animation, which means we don&#8217;t need to write a single line of JavaScript for the effect itself.</p>
<p>Currently, CSS3 keyframe animations are supported by Firefox, Safari and Chrome, so if you are using a recent version of one of these browsers, you will be able to enjoy the demo.</p>
<p>Here are some minor considerations that drove the decisions above:</p>
<ul>
<li>The image of the newspaper, encoded as PNG, weighs at over 250kb. Slicing it into independently encoded slices saves 200kb, as the center part does need transparency and is encoded as JPEG;</li>
<li>Rotating a bunch of DOM elements is slower than a single canvas element. Also, rotated text in the browser generally does not look very good, as letters may lose their anti-aliasing (see a <a href="http://jsfiddle.net/martinaglv/mXr3B/" target="_blank">simple experiment here</a>; it is most pronounced in Firefox). Painting the text and the newspaper background to a <code>canvas</code> element solves both of these problems;</li>
</ul>
<div id="attachment_1547" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/07/spinning-newspaper-effect-css3/"><img class="size-full wp-image-1547" title="The Sliced Newspaper Background" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/07/the-slices-spinning-newspaper-effect.jpg" alt="The Sliced Newspaper Background" width="620" height="320" /></a><p class="wp-caption-text">The Sliced Newspaper Background</p></div>
<h3>The HTML</h3>
<p>The markup of the page is minimal &#8211; everything is done using jQuery, so we only need to include our JS source files and stylesheets.</p>
<h4>index.html</h4>
<pre class="brush:html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta charset="utf-8" /&gt;
        &lt;title&gt;Spinning Newspaper Effect | Tutorialzine Demo&lt;/title&gt;

        &lt;!-- Our CSS stylesheet file --&gt;
        &lt;link rel="stylesheet" href="assets/css/styles.css" /&gt;

		&lt;!-- Embedding the Anton font from Google Webfonts --&gt;
        &lt;link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Anton&amp;v2" /&gt;

        &lt;!--[if lt IE 9]&gt;
          &lt;script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt;
        &lt;![endif]--&gt;
    &lt;/head&gt;

    &lt;body&gt;

		&lt;h3 id="fin"&gt;That is all&lt;/h3&gt;

		&lt;!--
			This div uses the "Anton" font,
			preloading it for the canvas element
        --&gt;
		&lt;div id="fontPreload"&gt;.&lt;/div&gt;

        &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"&gt;&lt;/script&gt;
        &lt;script src="assets/js/script.js"&gt;&lt;/script&gt;

    &lt;/body&gt;
&lt;/html&gt;</pre>
<p>In the head section, we include our <strong>styles.css</strong> file (discussed below) and a stylsheet, which embeds the <a href="http://www.google.com/webfonts/specimen/Anton" target="_blank">Anton font</a> from Google WebFonts. Near the end of the file, we include version 1.6.2 of the <strong>jQuery library</strong> and our <strong>script.js</strong> (discussed in detail later on).</p>
<p>The most important piece of markup in the code is also the most unassuming. The <code>#fontPreload</code> div is crucial for this example. What it does is use the embedded <em>Anton</em> web font. This is required so that browsers properly initializes the font before it is used in the canvas. Without it we would be staring at a blank newspaper cover.</p>
<div id="attachment_1548" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/07/spinning-newspaper-effect-css3/"><img class="size-full wp-image-1548" title="Spinning Newspaper Effect with CSS3 Animations" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/07/spinning-newspaper-effect-css3-animations.jpg" alt="Spinning Newspaper Effect with CSS3 Animations" width="620" height="460" /></a><p class="wp-caption-text">Spinning Newspaper Effect with CSS3 Animations</p></div>
<h3>The jQuery</h3>
<p>As we are using a custom web font, we need to be sure that the font is loaded before we use it to generate the newspaper titles. This is why we are binding a callback to the <code>$(window).load()</code> event, which is called once everything is loaded:</p>
<h4>assets/js/script.js</h4>
<pre class="brush:js">$(window).load(function(){

	var imgPath = "assets/img/";

	// Define 6 paper covers:

	var papers = [
		{
			line1:"The financial",
			line2:"chrisis is a hoax!",
			subtitle:"Economist admits practical joke"
		}, {
			line1:"Deeply fried now",
			line2:"considered healthy",
			subtitle:"Scientists change the definition of \"Healthy\""
		}, {
			line1:"Apple announces",
			line2:"the new iphone 9",
			subtitle:"5, 6, 7 and 8 deemed \"not hip enough\""
		}, {
			line1:"The world did end",
			line2:"on may 21st!",
			subtitle:"Priest argues we are actually dead"
		}, {
			line1:"France imposes an",
			line2:"internet kitten tax",
			subtitle:"Every cat picture on the internet will cost 3 €"
		}, {
			line1:"Thank you &amp;",
			line2:"goodbye",
			subtitle:"The Zine Weekly takes its farewell"
		}
	];

	// Check whether canvas and CSS3 animations are supported:

	if(!$.support.canvas){
		$('#fin').html('Sorry, your browser does not&lt;br /&gt;support &amp;lt;canvas&amp;gt;').show();
		return;
	}

	if(!$.support.css3Animation){
		$('#fin').html('Sorry, your browser does not&lt;br /&gt;support CSS3 Animations').show();
		return;
	}

	// Use jQuery.Deferred to bind a callback when all
	// the images that comprise the paper are loaded:

	$.when(

		loadImage(imgPath+"paper_top.png"),
		loadImage(imgPath+"paper_left.png"),
		loadImage(imgPath+"paper_center.jpg"),
		loadImage(imgPath+"paper_right.png"),
		loadImage(imgPath+"paper_bottom.png")

	).then(function( imgTop, imgLeft, imgCenter, imgRight, imgBottom ){

		// Loop through the paper covers and
		// create a new canvas for each one:

		$.each(papers,function(i){

			var canvas	= document.createElement("canvas"),
				c		= canvas.getContext("2d");

			canvas.width = 717;
			canvas.height = 526;

			// Drawing the paper background slices:

			c.drawImage( imgTop, 0, 0 );
			c.drawImage( imgLeft, 0, 12 );
			c.drawImage( imgCenter, 14, 12 );
			c.drawImage( imgRight, 711, 12 );
			c.drawImage( imgBottom, 0, 516 );

			// Drawing the text using our helper
			// function (see at the bottom):

			drawText( this.line1, this.line2, this.subtitle, c, 358, 250 );

			// Appending the element to the page.
			// This triggers the CSS3 animation.

			setTimeout(function(){
				$("body").append(canvas);
			},i*5800);

		});

		// "This is all"
		$('#fin').delay(papers.length*5800).fadeIn();
	});

	/*------------------------
		Helper functions
	------------------------*/

	// Load an image by URL and resolve a jQuery.Deferred:

	function loadImage(src){

		var def = new $.Deferred(),
			img = new Image();

		img.onload = function(){

			//	Resolve the deferred. The img parameter
			//	will be available in the then function:

			def.resolve(img);
		}

		// Always set the src attribute
		// after the onload callback:

		img.src = src;

		return def.promise();
	}

	// Draw two lines of text and a subtitle
	// on the canvas (passed as the c param):

	function drawText( line1, line2, subtitle, c, x, y ){

		c.font = "65px Anton,Calibri";
		c.textAlign = "center";
		c.fillStyle = "#3e3e3e";

		c.fillText(line1.toUpperCase(),x,y);
		c.fillText(line2.toUpperCase(),x,y+80);

		c.font = "italic 20px Georgia,serif";
		c.fillStyle = "#737373";

		c.fillText(subtitle,x,y+120);
	}
});

(function(){

	// Adding custom checks for canvas and css3
	// animations support, to the jQuery.support object:

	$.support.canvas = 'getContext' in document.createElement('canvas');

	$.support.css3Animation = (function(){
		var sp = $('&lt;span&gt;');

		return (
			sp.css("-webkit-animation") !== undefined	||
			sp.css("-moz-animation") !== undefined		||
			sp.css("animation") !== undefined
		);

	})();
})();</pre>
<p>To generate the newspapers, we need to first load the five slices that comprise the image. This sounds like the perfect place to use jQuery&#8217;s <strong>Deferred object</strong>, introduced in version 1.5. What it does is to notify us when a number of asynchronous events are completed. As you can see in the code above, we are using it in the <code>loadImage()</code> function. The <code>then()</code> method on line 58 is called only when all five images are loaded.</p>
<blockquote class="note"><p>Using jQuery.Deferred is a convenient way to organize our code better. It is also used by jQuery&#8217;s internal AJAX and animation methods. To get a better idea of what you can do with it, read through the <a href="http://api.jquery.com/category/deferred-object/" target="_blank">deferred object documentation</a>.</p></blockquote>
<p>Inside the <code>$.each</code> loop, we create a canvas element for each of the paper covers, and add them to the page after a delay introduced by the <code>setTimeout()</code> call.</p>
<p>Once we have the canvas on the page, we can continue with animating it.</p>
<h3>The CSS</h3>
<p>Canvas elements are treated as any other element. This means that you can safely style and transform them the same way as you would a regular image.</p>
<p>Once the canvas is added to the page, it will assume the styling you see below:</p>
<pre class="brush:css">canvas{
	position:fixed;
	width:717px;
	height:526px;

	top:50%;
	left:50%;

	margin:-263px 0 0 -358px;
	opacity:0;

	/* Configure the animation for Firefox */
	-moz-animation-duration:6s;
	-moz-animation-name:spin;
	-moz-animation-timing-function:linear;

	/* Configure it for Chrome and Safari */
	-webkit-animation-duration:6s;
	-webkit-animation-name:spin;
	-webkit-animation-timing-function:linear;
}</pre>
<p>Nothing out of the ordinary here. We are <a title="MicroTut: Centering a Div Both Horizontally And Vertically" href="http://tutorialzine.com/2010/03/centering-div-vertically-and-horizontally/" target="_blank">centering the canvas in the page</a>, and defining the different aspects of the animation like <strong><em>duration</em></strong>, <strong><em>name</em></strong>, and a <strong><em>timing function</em></strong>. &#8220;Linear&#8221; would make our animation run at a constant speed, instead of getting accelerated as is the case with &#8220;ease&#8221;, which is used by default.</p>
<p>After this, we have to use the <a href="https://developer.mozilla.org/en/CSS/CSS_animations" target="_blank">@keyframes declaration</a> to specify how our element would look at different key points during the animation:</p>
<pre class="brush:css">@-moz-keyframes spin{
	0%{
		opacity:0.2;
		-moz-transform:scale(0.2) rotate(0deg);
	}

	15%{
		opacity:1;
		margin:-263px 0 0 -358px;
		-moz-transform:scale(1) rotate(1090deg);
	}

	90%{
		opacity:1;
		top:50%;
		-moz-transform:scale(1) rotate(1090deg);
	}

	100%{
		top:500%;
		opacity:1;
		-moz-transform:scale(1) rotate(1090deg);
	}
}</pre>
<p>When the canvas element is added to the page, we start off from the <strong>0%</strong> position above. The element&#8217;s <em>opacity </em> is set to 0.2, and it is made 5 times smaller using a <code>scale()</code> transformation. It is quickly animated to its full size ( <code>scale(1)</code> ) in and from <strong>15%</strong> to <strong>90%</strong> of the animation (or about four and a half seconds) it stays fixed on the screen, after which it quickly falls outside the bottom border of the window (top is increased to 500%).</p>
<p>It is important to specify the properties that you want to persist in every percentage point of the animation. One example is the <code>-moz-transform:scale(1) rotate(1090deg)</code> declaration, which is duplicated three times. Without it, Chrome and Safari (but not Firefox) will revert to the default rotation of 0 degrees mid animation.</p>
<p>And, as this is still considered an experimental feature by browser vendors, we need to write the same code for webkit:</p>
<pre class="brush:css">@-webkit-keyframes spin{
	0%{
		opacity:0.2;
		-webkit-transform:scale(0.2) rotate(0deg);
	}
	15%{
		opacity:1;
		margin:-263px 0 0 -358px;
		-webkit-transform:scale(1) rotate(1090deg);
	}
	90%{
		opacity:1;
		top:50%;
		-webkit-transform:scale(1) rotate(1090deg);
	}

	100%{
		top:500%;
		opacity:1;
		-webkit-transform:scale(1) rotate(1090deg);
	}
}</pre>
<p><strong>With this our spinning newspaper effect is complete!</strong></p>
<h3>Conclusion</h3>
<p>As with any cop drama from the 1930s, and the 1930s themselves for that matter, this tutorial has to come to an end. Hope you folks had as much fun following the tutorial as I had writing it. If you have any thoughts or suggestion be sure to share in the comment section. You can also download a PSD with the newspaper template, so you can make your own, below.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/07/spinning-newspaper-effect-css3/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Creating a PHP and CSS3 Powered About Page</title>
		<link>http://tutorialzine.com/2011/07/about-page-vcard-php-css/</link>
		<comments>http://tutorialzine.com/2011/07/about-page-vcard-php-css/#comments</comments>
		<pubDate>Tue, 12 Jul 2011 19:46:46 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1530</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2011/07/about-page-vcard-php-css/"><img src="http://cdn.tutorialzine.com/img/featured/1530.jpg" /></a></div> Here we will be creating a simple about page that is powered by PHP, HTML5 and CSS3. It will present your contact information to your visitors, with an option for downloading it as a vCard (useful for importing it in third party applications).]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2011/07/about-page-vcard-php-css/"><img src="http://cdn.tutorialzine.com/img/featured/1530.jpg" /></a></div> <p>In this tutorial, we will be creating a simple about page that is powered by PHP, HTML5 and CSS3. It will present your contact information to your visitors, with an option for downloading it as a vCard (useful for importing it in third party applications).</p>
<p>You can use today&#8217;s example as a placeholder for your upcoming personal website, or as an actual about page.</p>
<h3>HTML</h3>
<p>As always, the first step is to write the HTML markup that will be powering our example. This is a simple page the main purpose of which is to present our contact details semantically. This will require adding appropriate meta tags and using the <a href="http://en.wikipedia.org/wiki/HCard" target="_blank">hCard microformat</a> to embed data in the page.</p>
<h4>index.php</h4>
<pre class="brush:html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta charset="utf-8" /&gt;
        &lt;meta name="description" content="Online info page of &lt;?php echo $profile-&gt;fullName()?&gt;. Learn more about me and download a vCard." /&gt;

        &lt;title&gt;Creating a PHP and CSS Powered About Page  | Tutorialzine Demo&lt;/title&gt;

        &lt;!-- Our CSS stylesheet file --&gt;
        &lt;link rel="stylesheet" href="assets/css/styles.css" /&gt;

        &lt;!--[if lt IE 9]&gt;
          &lt;script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt;
        &lt;![endif]--&gt;
    &lt;/head&gt;

    &lt;body&gt;

		&lt;section id="infoPage"&gt;

    		&lt;img src="&lt;?php echo $profile-&gt;photoURL()?&gt;" alt="&lt;?php echo $profile-&gt;fullName()?&gt;" width="164" height="164" /&gt;

            &lt;header&gt;
                &lt;h1&gt;&lt;?php echo $profile-&gt;fullName()?&gt;&lt;/h1&gt;
                &lt;h2&gt;&lt;?php echo $profile-&gt;tags()?&gt;&lt;/h2&gt;
            &lt;/header&gt;

            &lt;p class="description"&gt;&lt;?php echo nl2br($profile-&gt;description())?&gt;&lt;/p&gt;

            &lt;a href="&lt;?php echo $profile-&gt;facebook()?&gt;" class="grayButton facebook"&gt;Find me on Facebook&lt;/a&gt;
            &lt;a href="&lt;?php echo $profile-&gt;twitter()?&gt;" class="grayButton twitter"&gt;Follow me on Twitter&lt;/a&gt;

            &lt;ul class="vcard"&gt;
                &lt;li class="fn"&gt;&lt;?php echo $profile-&gt;fullName()?&gt;&lt;/li&gt;
                &lt;li class="org"&gt;&lt;?php echo $profile-&gt;company()?&gt;&lt;/li&gt;
                &lt;li class="tel"&gt;&lt;?php echo $profile-&gt;cellphone()?&gt;&lt;/li&gt;
                &lt;li&gt;&lt;a class="url" href="&lt;?php echo $profile-&gt;website()?&gt;"&gt;&lt;?php echo $profile-&gt;website()?&gt;&lt;/a&gt;&lt;/li&gt;
            &lt;/ul&gt;

		&lt;/section&gt;

        &lt;section id="links"&gt;
        	&lt;a href="?vcard" class="vcard"&gt;Download as V-Card&lt;/a&gt;
            &lt;a href="?json" class="json"&gt;Get as a JSON feed&lt;/a&gt;
            &lt;p&gt;In this tutorial: &lt;a href="http://www.flickr.com/photos/levycarneiro/4144428707/"&gt;Self Portrait&lt;/a&gt; by &lt;a href="http://www.flickr.com/photos/levycarneiro/"&gt;Levy Carneiro Jr&lt;/a&gt;&lt;/p&gt;
        &lt;/section&gt;

    &lt;/body&gt;
&lt;/html&gt;</pre>
<p>The <code>$profile</code> variable you see above, holds an object of the AboutPage PHP class that we will be writing in a moment. It holds our contact details and provides a number of useful methods for generating JSON and vCard files.</p>
<p>As mentioned above, we are using the hCard microformat to embed contact details in the page. This is a simple standard with which we use the class names of regular HTML elements to specify data, easily recognizable by search engines. The hCard holds information about our full name, organization, phone and home page:</p>
<pre class="brush:html">&lt;ul class="vcard"&gt;
    &lt;li class="fn"&gt;&lt;?php echo $profile-&gt;fullName()?&gt;&lt;/li&gt;
    &lt;li class="org"&gt;&lt;?php echo $profile-&gt;company()?&gt;&lt;/li&gt;
    &lt;li class="tel"&gt;&lt;?php echo $profile-&gt;cellphone()?&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a class="url" href="&lt;?php echo $profile-&gt;website()?&gt;"&gt;&lt;?php echo $profile-&gt;website()?&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</pre>
<p>You can also optionally specify a home / work address and other kinds of useful information.</p>
<div id="attachment_1534" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/07/about-page-vcard-php-css/"><img class="size-full wp-image-1534" title="PHP &amp; CSS3 Powered About Page" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/07/php-css3-html5-about-page.jpg" alt="PHP &amp; CSS3 Powered About Page" width="620" height="460" /></a><p class="wp-caption-text">PHP &amp; CSS3 Powered About Page</p></div>
<h3>PHP</h3>
<p>One of the points of using a server side language is that we can leave some aspects of the page to be generated on the fly. This frees us from having to manually keep various parts of the page up to date.</p>
<p>In the case with our about page, we have a simple configuration file, which holds the data, used by the page. This same resource is used for the generation of the vCard file and the JSON feed.</p>
<h4>config.php</h4>
<pre class="brush:php">$info = array(
	'firstName'		=&gt; 'John',
	'middleName'	=&gt; 'S.',
	'lastName'		=&gt; 'Smith',
	'photoURL'		=&gt; 'assets/img/photo.jpg',
	'birthDay'		=&gt; strtotime('22-03-1983'),
	'city'			=&gt; 'MyCity',
	'country'		=&gt; 'United States',
	'street'		=&gt; 'My Street 21',
	'zip'			=&gt; '12345',
	'company'		=&gt; 'Google Inc',
	'website'		=&gt; 'http://tutorialzine.com/',
	'email'			=&gt; 'email@example.com',
	'cellphone'		=&gt; '12345678910',
	'description'	=&gt; "I am a webdeveloper living in ...",
	'tags'			=&gt; 'Developer, Designer, Photographer',
	'facebook'		=&gt; 'http://www.facebook.com/',
	'twitter'		=&gt; 'http://twitter.com/Tutorialzine'
);</pre>
<p>Not all of these properties are presented on the about page. Some of them (like the <em>address fields</em>, <em>company</em>, <em>email</em> and <em>birthday</em>) are only made available when the user downloads the profile as a <em>vCard</em> or as a <em>JSON file</em>. You can also add quite a few more properties to this array (a complete list is given as a comment in the <em>config.php</em> file).</p>
<p>So now that we have provided all the information we wanted, we need to build a class that will handle the task of presenting a complete about page.</p>
<h4>aboutPage.class.php</h4>
<pre class="brush:php">class AboutPage{
	private $info = array();

	// The constructor:

	public function __construct(array $info){
		$this-&gt;info = $info;
	}

	// A helper method that assembles the person's full name:

	public function fullName(){
		return $this-&gt;firstName().' '.$this-&gt;middleName().' '.$this-&gt;lastName();
	}

	// Using PHP's Magick __call method to make the
	// properties of $this-&gt;info available as method calls:

	public function __call($method,$args = array()){

		if(!array_key_exists($method,$this-&gt;info)){
			throw new Exception('Such a method does not exist!');
		}

		if(!empty($args)){
			$this-&gt;info[$method] = $args[0];
		}
		else{
			return $this-&gt;info[$method];
		}
	}

	// This method generates a vcard from the $info
	// array, using the third party vCard class:

	public function downloadVcard(){

		$vcard = new vCard;

		$methodCalls = array();

		// Translating the properties of $info to method calls
		// understandable by the third party vCard class:

		$propertyMap = array(
			'firstName'		=&gt; 'setFirstName',
			'middleName'	=&gt; 'setMiddleName',
			'lastName'		=&gt; 'setLastName',
			'birthDay'		=&gt; 'setBirthday',
			'city'			=&gt; 'setHomeCity',
			'zip'			=&gt; 'setHomeZIP',
			'country'		=&gt; 'setHomeCountry',
			'website'		=&gt; 'setURLWork',
			'email'			=&gt; 'setEMail',
			'description'	=&gt; 'setNote',
			'cellphone'		=&gt; 'setCellphone');

		// Looping though the properties in $info:

		foreach($this-&gt;info as $k=&gt;$v){

			// Mapping a property of the array to a recognized method:

			if($propertyMap[$k]){
				$methodCalls[$propertyMap[$k]] = $v;
			}
			else {

				// If it does not exist, transform it to setPropertyName,
				// which might be recognized by the vCard class:

				$methodCalls['set'.ucfirst($k)] = $v;
			}
		}

		// Attempt to call these methods:

		foreach($methodCalls as $k=&gt;$v){
			if(method_exists($vcard,$k)){
				$vcard-&gt;$k($v);
			}
			else error_log('Invalid property in your $info array: '.$k);
		}

		// Serving the vcard with a x-vcard Mime type:

		header('Content-Type: text/x-vcard; charset=utf-8');
		header('Content-Disposition: attachment; filename="'.$this-&gt;fullName().'.vcf"');
		echo $vcard-&gt;generateCardOutput();
	}

	// This method generates and serves a JSON object from the data:

	public function generateJSON(){
		header('Content-Type: application/json');
		header('Content-Disposition: attachment; filename="'.$this-&gt;fullName().'.json"');

		// If you wish to allow cross-domain AJAX requests, uncomment the following line:
		// header('Access-Control-Allow-Origin: *');

		echo json_encode($this-&gt;info);
	}
}</pre>
<p>As you can see from the code below, we are using a <a href="http://www.phpclasses.org/package/874-PHP-class-for-creating-vCard-files.html" target="_blank">third party open source class</a> for the actual generation of the vCard file (vcf). As this class uses its own set of method calls, we will need to transform our configuration file to something that it will understand. We are doing this with the <code>$propertyMap</code> array which maps properties found in our $info array to the names of method calls that will need to be executed on the vCard object. After we configure the <code>$vcard</code> object, we set the content headers and call the object&#8217;s <code>generateCardOutput()</code> method. This causes the browser to display a file download dialog.</p>
<p>We are doing basically the same thing in the generateJSON method, with the worthy exception that we are not using a third party PHP class, but the <code>json_encode()</code> built-in. We are serving the JSON file with an application/json content type. You can also uncomment the access control header if you wish to be able to access your data via AJAX from other domains.</p>
<p>Now lets see how we are using this class in index.php:</p>
<h4>index.php</h4>
<pre class="brush:php">require 'includes/config.php';
require 'includes/aboutPage.class.php';
require 'includes/vcard.class.php';

$profile = new AboutPage($info);

if(array_key_exists('json',$_GET)){
	$profile-&gt;generateJSON();
	exit;
}
else if(array_key_exists('vcard',$_GET)){
	$profile-&gt;downloadVcard();
	exit;
}</pre>
<p>The fragment you see above is found at the top of <em>index.php</em>, before any of the HTML, as we have to be able to set headers. After including the appropriate PHP source files, we create a new <code>AboutPage</code> object with the configuration array as its parameter. After this we check whether the requested URL is <em>?json</em> or <em>?vcard</em>, and serve the appropriate data. Otherwise, the regular about page is displayed.</p>
<h3>CSS</h3>
<p>Most of the design of the about page is pretty straightforward. However, a fair share of CSS3 is used to keep the number of images to a minimum. The two buttons &#8211; <em>Find me on facebook</em>, and <em>Follow me on twitter</em>, that are positioned below the text, are ordinary hyperlinks with a <code>.grayButton</code> class name. You can see the definition of this class below:</p>
<h4>assets/css/styles.css</h4>
<pre class="brush:css">a.grayButton{
	padding:6px 12px 6px 30px;
	position:relative;

	background-color:#fcfcfc;
	background:-moz-linear-gradient(left top -90deg, #fff, #ccc);
	background:-webkit-linear-gradient(left top -90deg, #fff, #ccc);
	background:linear-gradient(left top -90deg, #fff, #ccc);

	-moz-box-shadow: 1px 1px 1px #333;
	-webkit-box-shadow: 1px 1px 1px #333;
	box-shadow: 1px 1px 1px #333;

	-moz-border-radius:18px;
	-webkit-border-radius:18px;
	border-radius:18px;

	font-size:11px;
	color:#444;
	text-shadow:1px 1px 0 #fff;
	display:inline-block;
	margin-right:10px;

	-moz-transition:0.25s;
	-webkit-transition:0.25s;
	transition:0.25s;
}

a.grayButton:hover{
	text-decoration:none !important;
	box-shadow:0 0 5px #2b99ff;
}

a.grayButton:before{
	background:url('../img/icons.png') no-repeat;
	height: 18px;
	left: 4px;
	position: absolute;
	top: 6px;
	width: 20px;
	content: '';
}

a.grayButton.twitter:before{
	background-position:0 -20px;
}</pre>
<p>The code above applies a CSS3 linear gradient to the button, text shadows and rounded corners. It also defines a 0.25 sec transition, that animates the glow that is applied on hover. We are also using the <code>:before</code> pseudo element to create the icon that goes with the button. As we are using a sprite, the only thing that differs between the two buttons is the offset of the background image.</p>
<p>After this we have the &#8220;<em>Download as vCard</em>&#8221; and &#8220;<em>Get as a JSON file</em>&#8221; links:</p>
<h4>assets/css/styles.css</h4>
<pre class="brush:css">#links{
	text-align:center;
	padding-top: 20px;
	border-top:1px solid #4a4a4a;
	text-shadow: 1px 1px 0 #333333;
	width:655px;
	margin:0 auto;
}

#links a{
	color: #ccc;
	position:relative;
}

#links &gt; a{
	display: inline-block;
	font-size: 11px;
	margin: 0 10px;
	padding-left:15px;
}

#links &gt; a:before{
	background: url("../img/icons.png") no-repeat -10px -60px;
	position:absolute;
	content:'';
	width:16px;
	height:16px;
	top:2px;
	left:-4px;
}

#links &gt; a.vcard:before{
	background-position: -10px -40px;
	top: 0;
	left: -8px;
}

#links p{
	color: #888888;
	font-size: 10px;
	font-style: normal;
	padding: 30px;
}</pre>
<p>As the <code>#links</code> section element contains more than these links (it contains a paragraph with a link to a great <a href="http://www.flickr.com/photos/levycarneiro/" target="_blank">portrait image by Levy Carneiro Jr.</a>) , we have to limit the styling to the anchor elements that are direct children of the section.</p>
<p><strong>With this our PHP &amp; CSS3 powered about page is complete!</strong></p>
<h3>To Wrap it up</h3>
<p>You can use this about page as a simple placeholder for your personal website. You can also use an existing users database and create beautiful profiles for your users. Combined with some of our previous tutorials, you can display your latest posts on facebook, flickr images or tweets as a personalized home page.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/07/about-page-vcard-php-css/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Making a Beautiful HTML5 Portfolio</title>
		<link>http://tutorialzine.com/2011/06/beautiful-portfolio-html5-jquery/</link>
		<comments>http://tutorialzine.com/2011/06/beautiful-portfolio-html5-jquery/#comments</comments>
		<pubDate>Fri, 17 Jun 2011 13:06:43 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1486</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2011/06/beautiful-portfolio-html5-jquery/"><img src="http://cdn.tutorialzine.com/img/featured/1486.jpg" /></a></div> In today's tutorial we will be making a beautiful HTML5 portfolio powered by jQuery and the Quicksand plugin. You can use it to showcase your latest work and it is fully customizable, so potentially you could expand it to do much more.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2011/06/beautiful-portfolio-html5-jquery/"><img src="http://cdn.tutorialzine.com/img/featured/1486.jpg" /></a></div> <p>In today&#8217;s tutorial we will be making a beautiful HTML5 portfolio powered by jQuery and the <a href="http://razorjack.net/quicksand/index.html" target="_blank">Quicksand plugin</a>. You can use it to showcase your latest work and it is fully customizable, so potentially you could expand it to do much more.</p>
<h3>The HTML</h3>
<p>The first step is to write down the markup of a new HTML5 document. In the head section, we will include the stylesheet for the page. The <em> jQuery library</em>, the <em>Quicksand </em>plugin and our <em>script.js</em> will go right  before the closing body tag:</p>
<h4>index.html</h4>
<pre class="brush:html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta charset="utf-8" /&gt;

        &lt;title&gt;Making a Beautiful HTML5 Portfolio | Tutorialzine Demo&lt;/title&gt;

        &lt;!-- Our CSS stylesheet file --&gt;
        &lt;link rel="stylesheet" href="assets/css/styles.css" /&gt;

		&lt;!-- Enabling HTML5 tags for older IE browsers --&gt;
        &lt;!--[if lt IE 9]&gt;
          &lt;script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt;
        &lt;![endif]--&gt;
    &lt;/head&gt;

    &lt;body&gt;

        &lt;header&gt;
            &lt;h1&gt;My Portfolio&lt;/h1&gt;
        &lt;/header&gt;

        &lt;nav id="filter"&gt;
			&lt;!-- The menu items will go here (generated by jQuery) --&gt;
		&lt;/nav&gt;

        &lt;section id="container"&gt;
        	&lt;ul id="stage"&gt;
				&lt;!-- Your portfolio items go here --&gt;
			&lt;/ul&gt;
        &lt;/section&gt;

        &lt;footer&gt;
        &lt;/footer&gt;

		&lt;!-- Including jQuery, the Quicksand plugin, and our own script.js --&gt;

        &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"&gt;&lt;/script&gt;
        &lt;script src="assets/js/jquery.quicksand.js"&gt;&lt;/script&gt;
        &lt;script src="assets/js/script.js"&gt;&lt;/script&gt;

    &lt;/body&gt;
&lt;/html&gt;</pre>
<p>In the body, there are a number of the new HTML5 elements. The <code>header</code> holds our h1 heading (which is styled as the logo), the <code>section</code> element holds the unordered list with the portfolio items (more lists are added by jQuery, as you will see later), and the <code>nav</code> element, styled as a green bar, acts as a content filter.</p>
<p>The <code>#stage</code> unordered list holds our portfolio items. You can see what these items should look like below. Each of them has a HTML5 <code>data</code> attribute, which defines a series of comma-separated tags. Later, when we use jQuery to loop through this list, we will record the tags and create categories that can be selected from the green bar.</p>
<pre class="brush:html">&lt;li data-tags="Print Design"&gt;
	&lt;img src="assets/img/shots/1.jpg" /&gt;
&lt;/li&gt;

&lt;li data-tags="Logo Design,Print Design"&gt;
	&lt;img src="assets/img/shots/2.jpg" /&gt;
&lt;/li&gt;

&lt;li data-tags="Web Design,Logo Design"&gt;
	&lt;img src="assets/img/shots/3.jpg" /&gt;
&lt;/li&gt;</pre>
<p>You can put whatever you want in these li items and customize the portfolio further. The Quicksand plugin will handle the animated transitions of this list, so you are free to experiment.</p>
<div id="attachment_1491" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/06/beautiful-portfolio-html5-jquery/"><img class="size-full wp-image-1491" title="Beautiful HTML5 Portfolio with jQuery" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/06/beautiful-html5-jquery-portfolio.jpg" alt="Beautiful HTML5 Portfolio with jQuery" width="620" height="460" /></a><p class="wp-caption-text">Beautiful HTML5 Portfolio with jQuery</p></div>
<h3>The jQuery</h3>
<p>What the Quicksand plugin does, is compare two unordered lists of items, find the matching LIs inside them, and animate them to their new positions. The jQuery script we will be writing in this section, will loop through the portfolio items in the <code>#stage</code> list, and create a new (hidden) unordered list for each of the tags it finds. It will also create a new menu option, which will trigger the quicksand transition between the two lists.</p>
<p>First we need to listen for the <code>ready</code> event (the earliest point in the loading of the page where we can access the DOM), and loop through all the li items detecting the associated tags.</p>
<h4>script.js &#8211; Part 1</h4>
<pre class="brush:js">$(document).ready(function(){

	var items = $('#stage li'),
		itemsByTags = {};

	// Looping though all the li items:

	items.each(function(i){
		var elem = $(this),
			tags = elem.data('tags').split(',');

		// Adding a data-id attribute. Required by the Quicksand plugin:
		elem.attr('data-id',i);

		$.each(tags,function(key,value){

			// Removing extra whitespace:
			value = $.trim(value);

			if(!(value in itemsByTags)){
				// Create an empty array to hold this item:
				itemsByTags[value] = [];
			}

			// Each item is added to one array per tag:
			itemsByTags[value].push(elem);
		});

	});</pre>
<p>Each tag is added to the <code>itemsByTags</code> object as an array. This would mean that <code>itemsByTags['Web Design']</code> would hold an array with all the items that have Web Design as one of their tags. We will use this object to create hidden unordered lists on the page for quicksand.</p>
<p>It would be best to create a helper function that will handle it for us:</p>
<h4>script.js &#8211; Part 2</h4>
<pre class="brush:js">function createList(text,items){

	// This is a helper function that takes the
	// text of a menu button and array of li items

	// Creating an empty unordered list:
	var ul = $('&lt;ul&gt;',{'class':'hidden'});

	$.each(items,function(){
		// Creating a copy of each li item
		// and adding it to the list:

		$(this).clone().appendTo(ul);
	});

	ul.appendTo('#container');

	// Creating a menu item. The unordered list is added
	// as a data parameter (available via .data('list')):

	var a = $('&lt;a&gt;',{
		html: text,
		href:'#',
		data: {list:ul}
	}).appendTo('#filter');
}</pre>
<p>This function takes the name of the group and an array with LI items as parameters. It then clones these items into a new UL and adds a link in the green bar.</p>
<p>Now we have to loop through all the groups and call the above function, and also listen for clicks on the menu items.</p>
<h4>script.js &#8211; Part 3</h4>
<pre class="brush:js">// Creating the "Everything" option in the menu:
createList('Everything',items);

// Looping though the arrays in itemsByTags:
$.each(itemsByTags,function(k,v){
	createList(k,v);
});

$('#filter a').live('click',function(e){
	var link = $(this);

	link.addClass('active').siblings().removeClass('active');

	// Using the Quicksand plugin to animate the li items.
	// It uses data('list') defined by our createList function:

	$('#stage').quicksand(link.data('list').find('li'));
	e.preventDefault();
});

// Selecting the first menu item by default:
$('#filter a:first').click();</pre>
<p>Great! Now that we have everything in place we can move on to styling the page.</p>
<h3>The CSS</h3>
<p>Styling the page itself is not that interesting (you can see the CSS for this in <em>assets/css/styles.css</em>). However what is more interesting is the green bar (or the #filter bar), which uses the <code>:before / :after</code> pseudo elements to add attractive corners on the sides of the bar. As these are positioned absolutely, they also grow together with the bar.</p>
<h4>styles.css</h4>
<pre class="brush:css">#filter {
	background: url("../img/bar.png") repeat-x 0 -94px;
	display: block;
	height: 39px;
	margin: 55px auto;
	position: relative;
	width: 600px;
	text-align:center;

	-moz-box-shadow:0 4px 4px #000;
	-webkit-box-shadow:0 4px 4px #000;
	box-shadow:0 4px 4px #000;
}

#filter:before, #filter:after {
	background: url("../img/bar.png") no-repeat;
	height: 43px;
	position: absolute;
	top: 0;
	width: 78px;
	content: '';

	-moz-box-shadow:0 2px 0 rgba(0,0,0,0.4);
	-webkit-box-shadow:0 2px 0 rgba(0,0,0,0.4);
	box-shadow:0 2px 0 rgba(0,0,0,0.4);
}

#filter:before {
	background-position: 0 -47px;
	left: -78px;
}

#filter:after {
	background-position: 0 0;
	right: -78px;
}

#filter a{
	color: #FFFFFF;
	display: inline-block;
	height: 39px;
	line-height: 37px;
	padding: 0 15px;
	text-shadow:1px 1px 1px #315218;
}

#filter a:hover{
	text-decoration:none;
}

#filter a.active{
	background: url("../img/bar.png") repeat-x 0 -138px;
	box-shadow:	1px 0 0 rgba(255, 255, 255, 0.2),
				-1px 0 0 rgba(255, 255, 255, 0.2),
				1px 0 1px rgba(0,0,0,0.2) inset,
				-1px 0 1px rgba(0,0,0,0.2) inset;
}</pre>
<div id="attachment_1492" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/06/beautiful-portfolio-html5-jquery/"><img class="size-full wp-image-1492" title="Before / After Elements" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/06/filter-before-after-elements.jpg" alt="Before / After Elements" width="620" height="260" /></a><p class="wp-caption-text">Before / After Elements</p></div>
<p>With this our beautiful HTML5 portfolio is complete!</p>
<h3>Conclusion</h3>
<p>You can use this template to present your work. The best thing about it is that it&#8217;s really easy to customize. You only need to change the contents of the initial LI items of the #stage list, and specify some new tags &#8211; the script will do the rest. If the visitor doesn&#8217;t have JavaScript enabled, they will still see all your portfolio items, which is also good for SEO purposes.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/06/beautiful-portfolio-html5-jquery/feed/</wfw:commentRss>
		<slash:comments>39</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using apc
Page Caching using apc
Object Caching 701/785 objects using apc
Content Delivery Network via cdn.tutorialzine.com

Served from: tutorialzine.com @ 2012-02-03 22:15:16 -->
