<?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>Mon, 14 May 2012 09:13:18 +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>Timeline Portfolio</title>
		<link>http://tutorialzine.com/2012/04/timeline-portfolio/</link>
		<comments>http://tutorialzine.com/2012/04/timeline-portfolio/#comments</comments>
		<pubDate>Mon, 02 Apr 2012 08:16:09 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1920</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2012/04/timeline-portfolio/"><img src="http://cdn.tutorialzine.com/img/featured/1920.jpg" /></a></div> This time we will be using the Timeline jQuery plugin as a dark themed portfolio in which you can showcase projects and important events in your career.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2012/04/timeline-portfolio/"><img src="http://cdn.tutorialzine.com/img/featured/1920.jpg" /></a></div> <p><a href="http://timeline.verite.co/" target="_blank">Timeline</a> is a jQuery plugin specialized in showing a chronological series of events. You can embed all kinds of media including tweets, videos and maps, and associate them with a date. With some design tweaks, this will make it perfect for a portfolio in which you showcase your work and interests.</p>
<h3>The HTML</h3>
<p>Timeline comes with a light colored theme by default. It is perfectly usable and in most cases would be exactly what you need. However, for our portfolio, a dark design would be a better fit, so we will customize it to our liking.</p>
<p>First, let&#8217;s look at the basic layout 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;Timeline Portfolio | Tutorialzine Demo&lt;/title&gt;

        &lt;!-- The default timeline stylesheet --&gt;
        &lt;link rel="stylesheet" href="assets/css/timeline.css" /&gt;
        &lt;!-- Our customizations to the theme --&gt;
        &lt;link rel="stylesheet" href="assets/css/styles.css" /&gt;

		&lt;!-- Google Fonts --&gt;
        &lt;link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Dancing+Script|Antic+Slab" /&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="timeline"&gt;
			&lt;!-- Timeline will generate additional markup here --&gt;
		&lt;/div&gt;

        &lt;!-- JavaScript includes - jQuery, turn.js and our own script.js --&gt;
		&lt;script src="http://code.jquery.com/jquery-1.7.1.min.js"&gt;&lt;/script&gt;
		&lt;script src="assets/js/timeline-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 have the plugin&#8217;s stylesheet &#8211; timeline.css, and styles.css, which will hold our customizations. In the footer we have the jQuery library, timeline plugin and <strong>script.js</strong> which initializes it.</p>
<p>When we call the plugin, it will search for a div on your page with the ID of <strong>timeline</strong>. Inside it, it will inserts all the markup it needs to present the timeline:</p>
<pre class="brush:html">&lt;div class="container main" id="timeline"&gt;
	&lt;div class="feature slider" style="overflow-y: hidden;"&gt;
		&lt;div class="slider-container-mask slider-container slider-item-container"&gt;

			&lt;!-- The divs below are the events of the timeline --&gt;

			&lt;div class="slider-item content"&gt;
				&lt;div class="text container"&gt;

					&lt;h2 class="start"&gt;Johnny B Goode&lt;/h2&gt;
					&lt;p&gt;&lt;em&gt;&lt;span class="c1"&gt;Designer&lt;/span&gt; &amp;amp; &lt;span class=
					"c2"&gt;Developer&lt;/span&gt;&lt;/em&gt;&lt;/p&gt;

				&lt;/div&gt;

				&lt;div class="media media-wrapper media-container"&gt;
					&lt;!-- Images or other media go here --&gt;
				&lt;/div&gt;
			&lt;/div&gt;

			&lt;div class="slider-item content content-container"&gt;
				&lt;div class="text container"&gt;

					&lt;h2 class="date"&gt;March 2009&lt;/h2&gt;
					&lt;h3&gt;My first experiment in time-lapse photography&lt;/h3&gt;
					&lt;p&gt;Nature at its finest in this video.&lt;/p&gt;

				&lt;/div&gt;

				&lt;div class="media media-wrapper media-container"&gt;
					&lt;!-- Images or other media go here --&gt;
				&lt;/div&gt;
			&lt;/div&gt;

			&lt;!-- More items go here --&gt;
		&lt;/div&gt;

        &lt;!-- Next arrow --&gt;
		&lt;div class="nav-next nav-container"&gt;
			&lt;div class="icon"&gt;&lt;/div&gt;
			&lt;div class="date"&gt;March 2010&lt;/div&gt;
			&lt;div class="title"&gt;Logo Design for a pet shop&lt;/div&gt;
		&lt;/div&gt;

        &lt;!-- Previous arrow --&gt;
		&lt;div class="nav-previous nav-container"&gt;
			&lt;div class="icon"&gt;&lt;/div&gt;
			&lt;div class="date"&gt;July 2009&lt;/div&gt;
			&lt;div class="title"&gt;Another time-lapse experiment&lt;/div&gt;
		&lt;/div&gt;
	&lt;/div&gt;

	&lt;div class="navigation"&gt;

			&lt;!-- The navigation items go here (the tooltips in the bottom)
                one for each of the events --&gt;

			&lt;div class="time"&gt;
				&lt;!-- The timeline numbers go here --&gt;
			&lt;/div&gt;
		&lt;/div&gt;

		&lt;div class="timenav-background"&gt;
			&lt;div class="timenav-line" style="left: 633px;"&gt;&lt;/div&gt;

			&lt;div class="timenav-interval-background top-highlight"&gt;&lt;/div&gt;
		&lt;/div&gt;

		&lt;div class="toolbar" style="top: 27px;"&gt;
			&lt;div class="back-home icon" title="Return to Title"&gt;&lt;/div&gt;
			&lt;div class="zoom-in icon" title="Expand Timeline"&gt;&lt;/div&gt;
			&lt;div class="zoom-out icon" data-original-title="Contract Timeline"&gt;&lt;/div&gt;
		&lt;/div&gt;
	&lt;/div&gt;
&lt;/div&gt;</pre>
<p>As we will be modifying the CSS of the timeline, the fragment above will give you a better idea of the customizations. Note that we won&#8217;t be recreating the plugin&#8217;s stylesheet from scratch, we will only be overriding some of the rules in our own css file. This has the benefit of making future updates to the plugin straightforward, not to mention that it will be much easier.</p>
<div id="attachment_1931" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2012/04/timeline-portfolio/"><img class="size-full wp-image-1931" title="Timeline Portfolio with jQuery" src="http://cdn.tutorialzine.com/wp-content/uploads/2012/03/timeline-portfolio-jquery.jpg" alt="Timeline Portfolio with jQuery" width="620" height="460" /></a><p class="wp-caption-text">Timeline Portfolio with jQuery</p></div>
<p>Writing the CSS by looking at the markup alone would be a tough undertaking, given that our rules must have <a href="http://css-tricks.com/specifics-on-css-specificity/" target="_blank">precedence</a> over the ones used in <em>timeline.css</em>. Fortunately, there is a much easier way, as you will see in the CSS section of this tutorial.</p>
<h3>The jQuery</h3>
<p>To initialize the plugin, we need to call the VMM.Timeline() method on document ready:</p>
<pre class="brush:js">$(function(){

	var timeline = new VMM.Timeline();
	timeline.init("data.json");

});</pre>
<p>The init method takes single argument &#8211; the data source. It can either be a json file like above, or a Google spreadsheet (reminiscent of our <a title="Dynamic FAQ Section w/ jQuery, YQL &amp; Google Docs" href="http://tutorialzine.com/2010/08/dynamic-faq-jquery-yql-google-docs/">Spredsheet Powered FAQ Tutorial</a>).</p>
<blockquote class="note"><p>For more information on the supported data sources, see the <a href="http://timeline.verite.co/#fileformat" target="_blank">documentation on the plugin&#8217;s site</a>, or browse the data.json file in the zip download for this tutorial.</p></blockquote>
<h3>The CSS</h3>
<p>I used Firebug&#8217;s HTML Inspector to get the right selectors for the elements that we are about to customize. In the HTML tab, it is easy to see what rules have been applied to each element by <em>timeline.css</em>. To override them, I copied the same selectors to <em>styles.css</em> which is where our modifications will take place. On several occurrences, however, I have used the <strong>!important</strong> flag to make my work easier.</p>
<p>All the customizations you see below override only a handful of CSS styles. The rest are inherited by the default stylesheet.<strong> Let&#8217;s begin!</strong></p>
<p>The first thing we will do in <strong>styles.css</strong>, after styling the page itself, is to change the backgrounds of the timeline:</p>
<pre class="brush:css">#timeline{
	background:none;
}

/* The individual events in the slider */
.slider .slider-container-mask .slider-container{
	background:none;
}

/* Setting a custom background image */
#timeline div.navigation{
    background: url('../img/timeline_bg.jpg') repeat;
    border-top:none;
}</pre>
<div id="attachment_1932" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2012/04/timeline-portfolio/"><img class="size-full wp-image-1932" title="Timeline Navigation with a CSS 3D Effect" src="http://cdn.tutorialzine.com/wp-content/uploads/2012/03/a-css-3d-effect.jpg" alt="Timeline Navigation with a CSS 3D Effect" width="620" height="260" /></a><p class="wp-caption-text">Timeline Navigation with a CSS 3D Effect</p></div>
<p>To create the 3D effect of the timeline navigation, we will need to use additional elements. But the Timeline plugin doesn&#8217;t include such in its markup. An easy solution is to use <strong>:before</strong> / <strong>:after</strong> pseudo elements. The :after element is the darker top part and it uses a linear gradient to enhance the effect.</p>
<pre class="brush:css">#timeline div.navigation:before{
	position:absolute;
	content:'';
	height:40px;
	width:100%;
	left:0;
	top:-40px;
	background: url('../img/timeline_bg.jpg') repeat;
}

#timeline div.navigation:after{
	position:absolute;
	content:'';
	height:10px;
	width:100%;
	left:0;
	top:-40px;
	background:repeat-x;

	background-image: linear-gradient(bottom, #434446 0%, #363839 100%);
	background-image: -o-linear-gradient(bottom, #434446 0%, #363839 100%);
	background-image: -moz-linear-gradient(bottom, #434446 0%, #363839 100%);
	background-image: -webkit-linear-gradient(bottom, #434446 0%, #363839 100%);
	background-image: -ms-linear-gradient(bottom, #434446 0%, #363839 100%);
}</pre>
<p>Then we add a dark background to the timeline navigation (the section with the small clickable tooltips that represent the events):</p>
<pre class="brush:css">#timeline div.timenav-background{
 	background-color:rgba(0,0,0,0.4) !important;

}

#timeline .navigation .timenav-background .timenav-interval-background{
	background:none;
}

#timeline .top-highlight{
	background-color:transparent !important;
}</pre>
<p>Later we style the zoom-in / zoom-out buttons and toolbar:</p>
<pre class="brush:css">#timeline .toolbar{
	border:none !important;
	background-color: #202222 !important;
}

#timeline .toolbar div{
	border:none !important;
}</pre>
<p>The numeric scale at the bottom comes next:</p>
<pre class="brush:css">#timeline .navigation .timenav .time .time-interval-minor .minor{
	margin-left:-1px;
}

#timeline .navigation .timenav .time .time-interval div{
	color: #CCCCCC;
}</pre>
<p>The previous and next arrows:</p>
<pre class="brush:css">.slider .nav-previous .icon {
	background: url("timeline.png") no-repeat scroll 0 -293px transparent;
}

.slider .nav-previous,.slider .nav-next{
	font-family:'Segoe UI',sans-serif;
}

.slider .nav-next .icon {
	background: url("timeline.png") no-repeat scroll 72px -221px transparent;
	width: 70px !important;
}

.slider .nav-next:hover .icon{
	position:relative;
	right:-5px;
}

.slider .nav-previous:hover, .slider .nav-next:hover {
    color: #666;
    cursor: pointer;
}

#timeline .thumbnail {
	border: medium none;
}</pre>
<p>The loading screen:</p>
<pre class="brush:css">#timeline .feedback {
	background-color: #222222;
	box-shadow: 0 0 30px rgba(0, 0, 0, 0.2) inset;
	border:none;
}

#timeline .feedback div{
	color: #AAAAAA;
	font-size: 14px !important;
	font-weight: normal;
}</pre>
<p>Then we move on to the slides:</p>
<pre class="brush:css">#timeline .slider-item h2,
#timeline .slider-item h3{
	font-family:'Antic Slab','Segoe UI',sans-serif;
}

#timeline .slider-item h2{
	color:#fff;
}

#timeline .slider-item p{
	font-family:'Segoe UI',sans-serif;
}

#timeline .slider-item img,
#timeline .slider-item iframe{
	border:none;
}</pre>
<p>Finally, we will customize the appearance of the front page. I am using <strong>nth-child(1)</strong> to target only the first slider-item, which contains the name and description of the timeline which have been defined in the JSON data source.</p>
<pre class="brush:css">/* Customizing the first slide - the cover */

#timeline .slider-item:nth-child(1) h2{
	font:normal 70px/1 'Antic Slab','Segoe UI',sans-serif;
	background:rgba(0,0,0,0.3);
	white-space: nowrap;
	padding:10px 5px 5px 20px;
	position:relative;
	right:-60px;
	z-index:10;
}

#timeline .slider-item:nth-child(1) p i{
	font:normal normal 40px 'Dancing Script','Segoe UI',sans-serif;
	background:rgba(0,0,0,0.3);
	white-space: nowrap;
	padding:5px 20px;
	position:relative;
	right:-60px;
	z-index:10;
}

#timeline .slider-item:nth-child(1) p .c1{
	color:#1bdff0;
}

#timeline .slider-item:nth-child(1) p .c2{
	color:#c92fe6;
}

#timeline .slider-item:nth-child(1) .media-container {
	left: -30px;
	position: relative;
	z-index: 1;
}

#timeline .slider-item:nth-child(1) .credit{
	text-align: center;
}</pre>
<p>The only thing left is to open up <em>timeline.psd</em> that is bundled with the download of the plugin, and change the color of some of the icons in photoshop. I have included the necessary files in the zip download for this tutorial. With this our timeline portfolio is complete!</p>
<h3>Done!</h3>
<p>You can use this portfolio to display not only your recent projects, but also interests and important moments of your career. Share your thoughts and suggestions in the comment section.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2012/04/timeline-portfolio/feed/</wfw:commentRss>
		<slash:comments>74</slash:comments>
		</item>
		<item>
		<title>Making a Page Flip Magazine with turn.js</title>
		<link>http://tutorialzine.com/2012/03/instagram-magazine-php-jquery/</link>
		<comments>http://tutorialzine.com/2012/03/instagram-magazine-php-jquery/#comments</comments>
		<pubDate>Fri, 16 Mar 2012 19:02:32 +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=1889</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2012/03/instagram-magazine-php-jquery/"><img src="http://cdn.tutorialzine.com/img/featured/1889.jpg" /></a></div> In this tutorial we are going to use PHP and the turn.js plugin, an implementation of the page flip effect with pure CSS3 and jQuery, to build an Instagram powered magazine.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2012/03/instagram-magazine-php-jquery/"><img src="http://cdn.tutorialzine.com/img/featured/1889.jpg" /></a></div> <p>The page flip effect used to be the quintessential Flash animation. On the web, it has powered everything from magazines to presentations, with its popularity declining over time, only to be reinvented on mobile devices as ebook reading apps.</p>
<p>In this tutorial we are going to use PHP and the <a href="http://www.turnjs.com/" target="_blank">turn.js plugin</a>, an implementation of the page flip effect with pure CSS3 and jQuery, to build a pretty magazine. We will fetch the most popular images from <a href="http://instagram.com/" target="_blank">Instagram</a> every hour, and use them as pages.</p>
<h3>HTML</h3>
<p>First we need to lay down the foundations of today&#8217;s example. We will use a single page design, which combines HTML5 markup and PHP in the same file for greater simplicity. You can see the resulting layout below:</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;Making an Instagram Magazine | Tutorialzine Demo&lt;/title&gt;

        &lt;!-- Our Stylesheet --&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="magazine" class="centerStart"&gt;

		&lt;!-- PHP will go here --&gt;

		&lt;/div&gt;

        &lt;!-- JavaScript includes - jQuery, turn.js and our own script.js --&gt;
		&lt;script src="http://code.jquery.com/jquery-1.7.1.min.js"&gt;&lt;/script&gt;
		&lt;script src="assets/js/turn.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 include <em>styles.css</em> in the head, and our JavaScript files at the bottom. The latter are the jQuery library, the turn.js plugin and script.js, where we will be initializing the plugin and listening for keyboard events. The PHP code that we will be writing in the next section will go in the <em>#magazine</em> div. PHP will have the job of generating the pages of our magazine, which will be used by turn.js.</p>
<p>As an example, here is the markup of the first three pages of the magazine:</p>
<h4>Generated code</h4>
<pre class="brush:html">&lt;div id="page1" class="page"&gt;
	&lt;div class="img1"&gt;

		&lt;!-- The pageNum span can be either on the left,
				or the right if the page is odd/even. --&gt;

		&lt;span class="pageNum right"&gt;1 // 32&lt;/span&gt;
		&lt;img src="assets/img/cover.jpg" alt="Cover" /&gt;
	&lt;/div&gt;
&lt;/div&gt;

&lt;div id="page2" class="page"&gt;
	&lt;div class="img2"&gt;
		&lt;span class="pageNum left"&gt;2 // 32&lt;/span&gt;
		&lt;img src="http://distilleryimage7.instagram.com/..." alt="Little tulips" /&gt;
	&lt;/div&gt;
&lt;/div&gt;

&lt;div id="page3" class="page"&gt;
	&lt;div class="img3"&gt;
		&lt;span class="pageNum right"&gt;3 // 32&lt;/span&gt;
		&lt;img src="http://distilleryimage2.instagram.com/..." alt="My style" /&gt;
	&lt;/div&gt;
&lt;/div&gt;</pre>
<p>The divs you see above are direct descendants of the #magazine div. This is the only requirement imposed by turn.js. You don&#8217;t need to have any special classes or data attributes for the elements to be interpreted as pages. With this we are ready to move on with the PHP code!</p>
<div id="attachment_1898" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2012/03/instagram-magazine-php-jquery/"><img class="size-full wp-image-1898" title="Page Flip Magazine with CSS3 and jQuery" src="http://cdn.tutorialzine.com/wp-content/uploads/2012/03/instagram-page-flip-magazine-jquery-php.jpg" alt="Page Flip Magazine with CSS3 and jQuery" width="620" height="460" /></a><p class="wp-caption-text">Page Flip Magazine with CSS3 and jQuery</p></div>
<h3>PHP</h3>
<p>PHP will have the task of communicating with Instagram&#8217;s API, caching the results, and generating the markup you saw above.</p>
<p>The first step is to register at the <a href="http://instagram.com/developer/" target="_blank">Instagram developer</a> website. After you obtain your <strong>client_id</strong> key, place it in <em><strong>index.php</strong></em> as the value of <code>$instagramClientID</code>. We won&#8217;t be needing any of the advanced functionality of the API, we will only be requesting the most popular images. This frees us from having to implement OAuth authentication, which would make today&#8217;s example significantly more complex.</p>
<blockquote class="note"><p>Note that if you want to modify the magazine and show photos other than the most popular, say your latest images, you will need to implement OAuth and authenticate your app to have access to your photos. <a href="http://instagr.am/developer/auth/" target="_blank">Consult the docs</a> for further information.</p></blockquote>
<p>Here is an example JSON response of the currently popular images on Instagram. I have omitted some of the attributes to make the code easier to read.</p>
<h4>Popular images JSON response</h4>
<pre class="brush:js">{    "meta": {
        "code": 200
    },
    "data": [{
        "tags": ["beautiful", "sky"],
        "location": "null",
        "comments": {
            "count": 31,
            "data": [...]
        },
        "filter": "Normal",
        "created_time": "1331910134",
        "link": "http:\/\/instagr.am\/p\/IPNNknqs84\/",
        "likes": {
            "count": 391,
            "data": [..]
        },
        "images": {
            "low_resolution": {
                "url": "http:\/\/distilleryimage8.instagram.com\/03c80dd86f7911e1a87612313804ec91_6.jpg",
                "width": 306,
                "height": 306
            },
            "thumbnail": {
                "url": "http:\/\/distilleryimage8.instagram.com\/03c80dd86f7911e1a87612313804ec91_5.jpg",
                "width": 150,
                "height": 150
            },
            "standard_resolution": {
                "url": "http:\/\/distilleryimage8.instagram.com\/03c80dd86f7911e1a87612313804ec91_7.jpg",
                "width": 612,
                "height": 612
            }
        },
        "caption": {
            "created_time": "1331910148",
            "text": "Goodnight.\ue056",
            "from": {
                "username": "jent99",
                "profile_picture": "http:\/\/images.instagram.com\/profiles\/profile_6227738_75sq_1319878922.jpg",
                "id": "6227738",
                "full_name": "jent99"
            },
            "id": "148395540733414783"
        },
        "type": "image",
        "id": "148395420004568888_6227738",
        "user": {
            "username": "jent99",
            "website": "",
            "bio": "Mostly nature pics.\ue32b\ue32b\ue32b Hope you like them.\ue056\ue32a     \ue334gi\ue334                    ",
            "profile_picture": "http:\/\/images.instagram.com\/profiles\/profile_6227738_75sq_1319878922.jpg",
            "full_name": "jent99",
            "id": "6227738"
        }
    }, {
		/* More photos here*/
	}]
}</pre>
<p>The API is limited to returning only 32 pics, but this is plenty for our example. You can see that each photo has three image sizes, but we will only be needing the standard one. There is also various other information that you can use like caption, dimensions, tags, comments, and more.</p>
<p>PHP will cache the results of this API call so we hit Instagram&#8217;s servers only once per hour. This will make our application more responsive and limit the number of calls.</p>
<h4>index.php</h4>
<pre class="brush:php">// You can obtain this client ID from the Instagram API page
$instagramClientID = '-- place your client id key here --';

$api = 'https://api.instagram.com/v1/media/popular?client_id='.$instagramClientID;
$cache = 'cache.txt';

if(file_exists($cache) &amp;&amp; filemtime($cache) &gt; time() - 60*60){
	// If a cache file exists, and it is
	// fresher than 1 hour, use it
	$images = unserialize(file_get_contents($cache));
}
else{
	// Make an API request and create the cache file

	// Fetch the 32 most popular images on Instagram
	$response = file_get_contents($api);

	$images = array();

	// Decode the response and build an array
	foreach(json_decode($response)-&gt;data as $item){

		$title = '';

		if($item-&gt;caption){
			$title = mb_substr($item-&gt;caption-&gt;text,0,70,"utf8");
		}

		$src = $item-&gt;images-&gt;standard_resolution-&gt;url;

		$images[] = array(
			"title" =&gt; htmlspecialchars($title),
			"src" =&gt; htmlspecialchars($src)
		);
	}

	// Remove the last item, so we still have
	// 32 items when when the cover is added
	array_pop($images);

	// Push the cover in the beginning of the array
	array_unshift($images,array("title"=&gt;"Cover", "src"=&gt;"assets/img/cover.jpg"));

	// Update the cache file
	file_put_contents($cache,serialize($images));
}

# Generate the markup
$totalPages = count($images);
foreach($images as $i=&gt;$image){

	?&gt;

	&lt;div id="page&lt;?php echo $i+1?&gt;" class="page"&gt;
		&lt;div class="img&lt;?php echo $i+1?&gt;"&gt;
			&lt;span class="pageNum &lt;?php echo ($i+1)%2? 'right' : 'left'?&gt;"&gt;&lt;?php echo $i+1?&gt; // &lt;?php echo $totalPages?&gt;&lt;/span&gt;
			&lt;img src="&lt;?php echo $image['src']?&gt;" alt="&lt;?php echo $image['title']?&gt;" /&gt;
		&lt;/div&gt;
	&lt;/div&gt;

	&lt;?php

}</pre>
<p>Caching is straightforward: we are using a temporary file &#8211; <em>cache.txt</em> &#8211; to store a serialized representation of the image array. If the cache file is non-existing or is older than an hour, we issue a new API request.</p>
<p>Notice the calls to <em><strong>array_pop</strong></em> and <em><strong>array_unshift</strong></em>. These are necessary as to make room for the custom cover image that is stored in <span style="text-decoration: underline;"><em>assets/img</em></span>. The magazine works best if we have an even number of pages, otherwise we would be unable to turn the last one, which would feel unnatural.</p>
<p>We are now ready for the plugin!</p>
<h3>jQuery</h3>
<p>Using turn.js is really simple. As we already have the markup of the magazine, we just need to call the turn() method. While we are at it, we will also listen for presses on the arrow keys, which will trigger page transitions.</p>
<h4>assets/js/script.js</h4>
<pre class="brush:js">$(function(){

	var mag = $('#magazine');

	// initiazlie turn.js on the #magazine div
	mag.turn();

	// turn.js defines its own events. We are listening
	// for the turned event so we can center the magazine
	mag.bind('turned', function(e, page, pageObj) {

		if(page == 1 &amp;&amp; $(this).data('done')){
			mag.addClass('centerStart').removeClass('centerEnd');
		}
		else if (page == 32 &amp;&amp; $(this).data('done')){
			mag.addClass('centerEnd').removeClass('centerStart');
		}
		else {
			mag.removeClass('centerStart centerEnd');
		}

	});

	setTimeout(function(){
		// Leave some time for the plugin to
		// initialize, then show the magazine
		mag.fadeTo(500,1);
	},1000);

	$(window).bind('keydown', function(e){

		// listen for arrow keys

		if (e.keyCode == 37){
			mag.turn('previous');
		}
		else if (e.keyCode==39){
			mag.turn('next');
		}

	});

});</pre>
<p>You can read more about what events the plugin emits and how to use them, in the <a href="https://github.com/blasten/turn.js/wiki/Reference" target="_blank">turn.js reference</a>.</p>
<p>Now let&#8217;s make it pretty!</p>
<h3>CSS</h3>
<p>We need to set explicit dimensions of the magazine and style the pages and page numbers. turn.js will handle the rest.</p>
<h4>assets/css/styles.css</h4>
<pre class="brush:css">#magazine{
	width:1040px;
	height:520px;
	margin:0 auto;
	position:relative;
	left:0;

	opacity:0;

	-moz-transition:0.3s left;
	-webkit-transition:0.3s left;
	transition:0.3s left;
}

#magazine .page{
	width:520px;
	height:520px;
	background-color:#ccc;
	overflow:hidden;
}

/* Center the magazine when the cover is shown */
#magazine.centerStart{
	left:-260px;
}

/* Center the magazine when the last page is shown */
#magazine.centerEnd{
	left:260px;
}

.page img{
	height:520px;
	width:520px;
	display:block;
}

/* Show a dark shadow when the cover is shown */
.centerStart .turn-page-wrapper:first-child{
	box-shadow:0 0 10px #040404;
}

/* Page Numbers */

span.pageNum{
    background-color: rgba(0, 0, 0, 0.3);
    bottom: 25px;
    box-shadow: 0 0 3px rgba(0, 0, 0, 0.25);
    color: #FFFFFF;
    font-size: 11px;
    height: 24px;
    line-height: 22px;
    opacity: 0.9;
    position: absolute;
    text-align: center;
    width: 55px;
}

span.pageNum.left{
	left:0;
	right:auto;
}

span.pageNum.right{
	left:auto;
	right:0;
}

/* Hide the page number on the cover */
#page1 .pageNum{
	display:none;
}</pre>
<p>With this our magazine is complete!</p>
<h3>We&#8217;re done!</h3>
<p>This example works in all recent browsers &#8211; Firefox, Chrome, Safari, Opera and even IE. It is even usable on iOS and Android. You can use this effect as part of photo galleries, templates or even real magazines. However you will have to create a fallback version for older browsers, which don&#8217;t have what it takes to display it properly.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2012/03/instagram-magazine-php-jquery/feed/</wfw:commentRss>
		<slash:comments>39</slash:comments>
		</item>
		<item>
		<title>Making an Impressive Product Showcase with CSS3</title>
		<link>http://tutorialzine.com/2012/02/css3-product-showcase/</link>
		<comments>http://tutorialzine.com/2012/02/css3-product-showcase/#comments</comments>
		<pubDate>Wed, 29 Feb 2012 19:00:36 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1865</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2012/02/css3-product-showcase/"><img src="http://cdn.tutorialzine.com/img/featured/1865.jpg" /></a></div> Impress.js is a small, standalone library that makes it easy to design advanced CSS3 presentations with eye-catching effects. But what if we used impress.js for something other than a presentation?]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2012/02/css3-product-showcase/"><img src="http://cdn.tutorialzine.com/img/featured/1865.jpg" /></a></div> <p>A product page is any page on your website that showcases a product. It has to describe its features, give some screenshots, and be descriptive. Naturally, this is the place where you build up the visitor&#8217;s interest towards your product,  but it is getting increasingly difficult to be original in grabbing their attention. Luckily, a new compact JavaScript library can help you make a splash.</p>
<p><a href="https://github.com/bartaz/impress.js/" target="_blank">impress.js</a> is a small, standalone library that makes it easy to design advanced CSS3 presentations with <a href="http://bartaz.github.com/impress.js/" target="_blank">eye-catching effects</a>. But what if we used impress.js for something other than a presentation? This is what we are doing today &#8211; we will be spicing up a plain old product page with some CSS3 magic!</p>
<h3>The HTML</h3>
<p>We start of with a simple HTML5 document that will be the backbone of today&#8217;s example.</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;Impressive CSS3 Product Showcase | Tutorialzine Demo&lt;/title&gt;

        &lt;!-- Google Webfonts and our stylesheet --&gt;
        &lt;link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans+Narrow|Open+Sans:300" /&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="impress" class="impress-not-supported"&gt;

			&lt;!-- The Slides Will Go Here --&gt;

		&lt;/div&gt;

		&lt;a id="arrowLeft" class="arrow"&gt;&amp;lt;&lt;/a&gt;
		&lt;a id="arrowRight" class="arrow"&gt;&amp;gt;&lt;/a&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/js/impress.js"&gt;&lt;/script&gt;
		&lt;script src="assets/js/script.js"&gt;&lt;/script&gt;

    &lt;/body&gt;
&lt;/html&gt;</pre>
<p>Nothing unusual here. Along with the Google Webfonts include in the head, we also have our main stylesheet (we will go back to it in the next section) and a number of JavaScript source files before the closing body tag.</p>
<p>The <strong>#impress</strong> div will hold the slides. The id is required in order to be recognized by <strong>impress.js</strong> (you can override this by passing a different id to the impress function call in script.js). After this, we have the arrows that initiate the slide transitions.</p>
<p>Last on the page, we have our JavaScript source files. <em>impress.js</em> is standalone and does not need jQuery to work, but we will be including it so we can listen for clicks on the arrows in our <em>script.js</em> file.</p>
<div id="attachment_1866" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2012/02/css3-product-showcase/"><img class="size-full wp-image-1866" title="CSS3 Product Showcase" src="http://cdn.tutorialzine.com/wp-content/uploads/2012/02/css3-product-showcase.jpg" alt="CSS3 Product Showcase" width="620" height="460" /></a><p class="wp-caption-text">CSS3 Product Showcase</p></div>
<p>Each of the slides of our showcase contains three elements &#8211; a <strong>title</strong>, a <strong>paragraph</strong> of text, and a smartphone <strong>image</strong>. These are all positioned uniquely for each slide. The promo images and text for this example were taken from <a href="http://www.google.com/nexus/">Google&#8217;s Galaxy Nexus web site</a>.</p>
<p>The elements of the slides are grouped into individual &#8220;<em>step</em>&#8221; divs inside the #impress container. With this we have set the stage for <strong>impress.js</strong>!</p>
<h3>Using impress.js</h3>
<p>With this tiny library, we can create smooth CSS3 transitions between the slides of our showcase. To do this, we have to instruct impress.js on how to orient the slides. This is easy to do &#8211; we will use data attributes on the step divs. These attributes are translated into real CSS3 transformations by the library, depending on the current browser, and affect the slide.</p>
<p>Impress.js supports a number of attributes:</p>
<ul>
<li><strong>data-x</strong>, <strong>data-y</strong>, <strong>data-z</strong> will move the slide on the screen in 3D space;</li>
<li><strong><strong>data-rotate</strong>, data-rotate-x</strong>, <strong>data-rotate-y</strong><strong></strong> rotate the element around the specified axis (in degrees);</li>
<li><strong>data-scale</strong> &#8211; enlarges or shrinks the slide.</li>
</ul>
<p>You can see the markup for the slides below:</p>
<pre class="brush:html">&lt;!-- The first slide retains its default position. We could omit the data attributes --&gt;
&lt;div id="intro" class="step" data-x="0" data-y="0"&gt;
	&lt;h2&gt;Introducing Galaxy Nexus&lt;/h2&gt;
	&lt;p&gt;Android 4.0&lt;br /&gt; Super Amoled 720p Screen&lt;br /&gt;
	&lt;img src="assets/img/nexus_1.jpg" width="232" height="458" alt="Galaxy Nexus" /&gt;
&lt;/div&gt;

&lt;!-- We are offsetting the second slide, rotating it and making it 1.8 times larger --&gt;
&lt;div id="simplicity" class="step" data-x="1100" data-y="1200" data-scale="1.8" data-rotate="190"&gt;
	&lt;h2&gt;Simplicity in Android 4.0&lt;/h2&gt;
	&lt;p&gt;Android 4.0, Ice Cream Sandwich brings an entirely new look and feel..&lt;/p&gt;
	&lt;img src="assets/img/nexus_2.jpg" width="289" height="535" alt="Galaxy Nexus" /&gt;
&lt;/div&gt;

&lt;!-- Same for the rest.. --&gt;
&lt;div id="connect" class="step" data-x="-300" data-y="600" data-scale="0.2" data-rotate="270"&gt;
	&lt;h2&gt;Connect &amp;amp; Share&lt;/h2&gt;
	&lt;p&gt;Real-life sharing is nuanced and rich. Galaxy Nexus makes sharing.. &lt;/p&gt;
	&lt;img src="assets/img/nexus_3.jpg" width="558" height="329" alt="Galaxy Nexus" /&gt;
&lt;/div&gt;

&lt;div id="upload" class="step" data-x="-200" data-y="1500" data-rotate="180"&gt;
	&lt;h2&gt;Instant Upload&lt;/h2&gt;
	&lt;p&gt;Your photos upload themselves with Instant Upload, which makes ..&lt;/p&gt;
	&lt;img src="assets/img/nexus_4.jpg" width="248" height="510" alt="Galaxy Nexus" /&gt;
&lt;/div&gt;

&lt;div id="music" class="step" data-x="-1200" data-y="1000" data-scale="0.8" data-rotate="270"&gt;
	&lt;h2&gt;Jam on with Google Music&lt;/h2&gt;
	&lt;p&gt;Google Music makes discovery, purchase, and listening effortless and..&lt;/p&gt;
	&lt;img src="assets/img/nexus_5.jpg" width="570" height="389" alt="Galaxy Nexus" /&gt;
&lt;/div&gt;</pre>
<p>When the slideshow starts, <em>impress.js</em> will compensate for these transformations, and apply the reverse rules to the #impress div with a smooth CSS transition. The result is the eye-catching presentation you see in the demo. Of course, this comes at the price that you have to manually tweak the data attributes of each slide for the best result.</p>
<h3>The CSS</h3>
<p>To make the presentation work, we will have to apply some CSS rules. The first step is to style the presentation container and declare default styling for the slide elements.</p>
<h4>assets/css/style.css</h4>
<pre class="brush:css">/*----------------------------
	Styling the presentation
-----------------------------*/

#impress:not(.impress-not-supported) .step{
	opacity:0.4;
}

#impress .step{
	width:700px;
	height: 600px;
	position:relative;
	margin:0 auto;

	-moz-transition:1s opacity;
	-webkit-transition:1s opacity;
	transition:1s opacity;
}

#impress .step.active{
	opacity:1;
}

#impress h2{
	font: normal 44px/1.5 'PT Sans Narrow', sans-serif;
	color:#444648;
	position:absolute;
	z-index:10;
}

#impress p{
	font: normal 18px/1.3 'Open Sans', sans-serif;
	color:#27333f;
	position:absolute;
	z-index:10;
}

#impress img{
	position:absolute;
	z-index:1;
}</pre>
<p>As you can see in the rules above, and in the HTML fragment in the beginning of this tutorial, the #impress container is assigned a <strong>.impress-not-supported</strong> class. The class is removed only if the current browser supports the functionality required for the library to run successfully.</p>
<p>Now we need to style the individual slides. I will only include the classes for the first slide here, you can find the rest in <em>assets/css/styles.css</em>.</p>
<pre class="brush:css">/*----------------------------
	Slide 1 - Intro
-----------------------------*/

#impress #intro{
	width: 500px;
}

#intro h2{
	text-align: center;
    width: 100%;
}

#intro p{
	font-size: 22px;
    left: 290px;
    line-height: 1.6;
    top: 220px;
    white-space: nowrap;
}

#intro img{
	top: 120px;
}</pre>
<p>All that is left is for a quick JS snippet to initiate impress.js, and listen for clicks on the arrows.</p>
<h3>jQuery</h3>
<p>To initialize the impress library we need to call the method of the same name. This will also return a new object, with methods for showing the previous / next slides.</p>
<h4>script.js</h4>
<pre class="brush:js">$(function(){

	var imp = impress();

	$('#arrowLeft').click(function(e){
		imp.prev();
		e.preventDefault();
	});

	$('#arrowRight').click(function(e){
		imp.next();
		e.preventDefault();
	});

});</pre>
<p><em>With this our impress-ive product showcase is complete!</em></p>
<h3>Done!</h3>
<p>You can use this example for product and landing pages, feature showcases and with some randomization you could even turn it into an image gallery.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2012/02/css3-product-showcase/feed/</wfw:commentRss>
		<slash:comments>58</slash:comments>
		</item>
		<item>
		<title>Apple-like Login Form with CSS 3D Transforms</title>
		<link>http://tutorialzine.com/2012/02/apple-like-login-form/</link>
		<comments>http://tutorialzine.com/2012/02/apple-like-login-form/#comments</comments>
		<pubDate>Fri, 17 Feb 2012 16:21:13 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1848</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2012/02/apple-like-login-form/"><img src="http://cdn.tutorialzine.com/img/featured/1848.jpg" /></a></div> This time we will use the new CSS3 3D transformations to add interesting effects to an Apple-inspired login form.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2012/02/apple-like-login-form/"><img src="http://cdn.tutorialzine.com/img/featured/1848.jpg" /></a></div> <p>Hey did you know that you can flip elements in 3D space with CSS3? You probably should as this has been possible for nearly two years. First only in Webkit browsers &#8211; Safari and Chrome, but now in Firefox as well. This means that more than half of the world (that use a non IE browser) can see advanced, CSS driven animations and effects.</p>
<p>In this tutorial we will see how we can use these transforms to create an interesting flipping effect on an Apple-inspired form.</p>
<h3>The Idea</h3>
<p>We will have two forms &#8211; login and password recovery, with only one visible at a time. Clicking a link (the ribbons in the example), will trigger a CSS3 rotation on the Y axis, which will reveal the other form with a flipping effect.</p>
<p>We will use jQuery to listen for clicks on the links, and add or remove a class name on the forms&#8217; container element. With CSS we will apply the <strong>rotateY</strong> transformation (a horizontal rotation) to both forms, but with a <em>180deg</em> difference depending on this class. This will make the forms appear on opposite sides of an imaginary platform. To animate the transition, we will use the <a href="https://developer.mozilla.org/en/CSS/CSS_transitions" target="_blank">CSS transition</a> property.</p>
<blockquote class="note"><p>Learn more about <a href="http://www.w3schools.com/css3/css3_3dtransforms.asp" target="_blank">CSS3 3D transforms</a>, read an <a href="http://24ways.org/2010/intro-to-css-3d-transforms" target="_blank">intro</a> or see <a href="http://hacks.mozilla.org/2011/10/css-3d-transformations-in-firefox-nightly/" target="_blank">some demos</a>.</p></blockquote>
<h3>The markup</h3>
<p>We need two forms &#8211; <em>login</em> and <em>recover</em>. Each form will have a submit button, and text/password inputs:</p>
<h4>index.html</h4>
<pre class="brush:html">		&lt;div id="formContainer"&gt;
			&lt;form id="login" method="post" action="./"&gt;
				&lt;a href="#" id="flipToRecover" class="flipLink"&gt;Forgot?&lt;/a&gt;
				&lt;input type="text" name="loginEmail" id="loginEmail" placeholder="Email" /&gt;
				&lt;input type="password" name="loginPass" id="loginPass" placeholder="Password" /&gt;
				&lt;input type="submit" name="submit" value="Login" /&gt;
			&lt;/form&gt;
			&lt;form id="recover" method="post" action="./"&gt;
				&lt;a href="#" id="flipToLogin" class="flipLink"&gt;Forgot?&lt;/a&gt;
				&lt;input type="text" name="recoverEmail" id="recoverEmail" placeholder="Your Email" /&gt;
				&lt;input type="submit" name="submit" value="Recover" /&gt;
			&lt;/form&gt;
		&lt;/div&gt;</pre>
<p>Note the IDs of the elements in the form. We will be using them extensively in the CSS part. Only one of these forms will be visible at a time. The other will be revealed during the flip animation. Each form has a <em>flipLink</em> anchor. Clicking this will toggle (add or remove) the <strong>flipped</strong> class name on the <em>#formContainer</em> div, which will in turn trigger the CSS3 animation.</p>
<div id="attachment_1849" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2012/02/apple-like-login-form/"><img class="size-full wp-image-1849" title="Apple-like Form with CSS 3D Transforms" src="http://cdn.tutorialzine.com/wp-content/uploads/2012/02/apple-like-form-css-3d.jpg" alt="Apple-like Form with CSS 3D Transforms" width="620" height="460" /></a><p class="wp-caption-text">Apple-like Form with CSS 3D Transforms</p></div>
<h3>The jQuery Code</h3>
<p>The first important step is to determine whether the current browser supports CSS3 3D transforms at all. If it doesn&#8217;t, we will provide a fallback (the forms will be switched directly). We will also use jQuery to listen for clicks on the <em>flipLink</em> anchors. As we will not be building an actual backend to these forms we will also need to prevent them from being submitted.</p>
<p>Here is the code that does all of the above:</p>
<h4>assets/js/script.js</h4>
<pre class="brush:js">$(function(){

	// Checking for CSS 3D transformation support
	$.support.css3d = supportsCSS3D();

	var formContainer = $('#formContainer');

	// Listening for clicks on the ribbon links
	$('.flipLink').click(function(e){

		// Flipping the forms
		formContainer.toggleClass('flipped');

		// If there is no CSS3 3D support, simply
		// hide the login form (exposing the recover one)
		if(!$.support.css3d){
			$('#login').toggle();
		}
		e.preventDefault();
	});

	formContainer.find('form').submit(function(e){
		// Preventing form submissions. If you implement
		// a backend, you will want to remove this code
		e.preventDefault();
	});

	// A helper function that checks for the
	// support of the 3D CSS3 transformations.
	function supportsCSS3D() {
		var props = [
			'perspectiveProperty', 'WebkitPerspective', 'MozPerspective'
		], testDom = document.createElement('a');

		for(var i=0; i&lt;props.length; i++){
			if(props[i] in testDom.style){
				return true;
			}
		}

		return false;
	}
});</pre>
<p>For convenience, the functionality that checks for 3D CSS3 support is extracted into a separate helper function. It checks for support of the <a href="https://developer.mozilla.org/en/CSS/perspective" target="_blank">perspective</a> property, which is what gives our demo a depth.</p>
<p>We can now move on to the CSS part.</p>
<div id="attachment_1850" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2012/02/apple-like-login-form/"><img class="size-full wp-image-1850" title="Password Recovery" src="http://cdn.tutorialzine.com/wp-content/uploads/2012/02/password-recovery.jpg" alt="Password Recovery" width="620" height="400" /></a><p class="wp-caption-text">Password Recovery</p></div>
<h3>The CSS</h3>
<p>CSS will handle everything from the presentation of the forms and form elements, to the animated effects and transitions. We&#8217;ll start with the form container styles.</p>
<h4>assets/css/styles.css</h4>
<pre class="brush:css">#formContainer{
	width:288px;
	height:321px;
	margin:0 auto;
	position:relative;

	-moz-perspective: 800px;
	-webkit-perspective: 800px;
	perspective: 800px;
}</pre>
<p>As well as a <em>width</em>, <em>height</em>, <em>margin</em> and <em>positioning</em>, we also set the <strong>perspective</strong> of the element. This property gives depth to the stage. Without it the animations would appear flat (try disabling it to see what I mean). The greater the value, the farther away the vanishing point.</p>
<p>Next we&#8217;ll style the forms themselves.</p>
<pre class="brush:css">#formContainer form{
	width:100%;
	height:100%;
	position:absolute;
	top:0;
	left:0;

	/* Enabling 3d space for the transforms */
	-moz-transform-style: preserve-3d;
	-webkit-transform-style: preserve-3d;
	transform-style: preserve-3d;

	/* When the forms are flipped, they will be hidden */
	-moz-backface-visibility: hidden;
	-webkit-backface-visibility: hidden;
	backface-visibility: hidden;

	/* Enabling a smooth animated transition */
	-moz-transition:0.8s;
	-webkit-transition:0.8s;
	transition:0.8s;

	/* Configure a keyframe animation for Firefox */
	-moz-animation: pulse 2s infinite;

	/* Configure it for Chrome and Safari */
	-webkit-animation: pulse 2s infinite;
}

#login{
	background:url('../img/login_form_bg.jpg') no-repeat;
	z-index:100;
}

#recover{
	background:url('../img/recover_form_bg.jpg') no-repeat;
	z-index:1;
	opacity:0;

	/* Rotating the recover password form by default */
	-moz-transform:rotateY(180deg);
	-webkit-transform:rotateY(180deg);
	transform:rotateY(180deg);
}</pre>
<p>We first describe the common styles that are shared between both forms. After this we add the unique styles that differentiate them.</p>
<p>The <strong>backface visibility</strong> property is important, as it instructs the browser to hide the backside of the forms. Otherwise we would end up with a mirrored version of the recover form instead of showing the login one. The flip effect is achieved using the <code>rotateY(180deg)</code> transformation. It rotates the element right to left. And as we&#8217;ve declared a <em>transition</em> property, every rotation will be smoothly animated.</p>
<p>Notice the <strong>keyframe</strong> declaration at the bottom of the form section. This defines a repeating (declared by the <em>infinite</em> keyword) <a href="https://developer.mozilla.org/en/CSS/CSS_animations" target="_blank">keyframe animation</a>, which does not depend on user interaction. The CSS description of the animation is given below:</p>
<pre class="brush:css">/* Firefox Keyframe Animation */
@-moz-keyframes pulse{
	0%{		box-shadow:0 0 1px #008aff;}
	50%{	box-shadow:0 0 8px #008aff;}
	100%{	box-shadow:0 0 1px #008aff;}
}

/* Webkit keyframe animation */
@-webkit-keyframes pulse{
	0%{		box-shadow:0 0 1px #008aff;}
	50%{	box-shadow:0 0 10px #008aff;}
	100%{	box-shadow:0 0 1px #008aff;}
}</pre>
<p>Each of the percentage groups corresponds to a time point in the animation. As it is repeating the box shadow will appear as a soft pulsating light.</p>
<p>Now let us see what happens once we&#8217;ve clicked the link, and the <strong>flipped</strong> class is added to <em>#formContainer</em>:</p>
<pre class="brush:css">#formContainer.flipped #login{

	opacity:0;

	/**
	 * Rotating the login form when the
	 * flipped class is added to the container
	 */

	-moz-transform:rotateY(-180deg);
	-webkit-transform:rotateY(-180deg);
	transform:rotateY(-180deg);
}

#formContainer.flipped #recover{

	opacity:1;

	/* Rotating the recover div into view */
	-moz-transform:rotateY(0deg);
	-webkit-transform:rotateY(0deg);
	transform:rotateY(0deg);
}</pre>
<p>The flipped class causes the <em>#login</em> and <em>#recover</em> div to get rotated by 180 degrees. This makes the #login form disappear. But as the #recover one was already facing us with its back side, it gets shown instead of hidden.</p>
<p>The opacity declarations here are only a fix for a bug in the Android browser, which ignores the backface-visibility property and shows a flipped version of the forms instead of hiding them. With this fix, the animation works even on Android and iOS in addition to desktop browsers.</p>
<h3>Done!</h3>
<p>CSS 3D transforms open the doors to all kinds of interesting effects, once reserved only for heavy flash web pages. Now we can have lightweight, crawlable and semantic sites that both look good and provide proper fallbacks for subpar browsers.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2012/02/apple-like-login-form/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<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>69</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>33</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>29</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>32</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>87</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>26</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 704/760 objects using apc
Content Delivery Network via cdn.tutorialzine.com

Served from: tutorialzine.com @ 2012-05-21 03:24:14 -->
