<?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; jQuery</title>
	<atom:link href="http://tutorialzine.com/category/tutorials/jquery-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>How to use Geolocation and Yahoo&#8217;s APIs to build a simple weather webapp</title>
		<link>http://tutorialzine.com/2012/05/weather-forecast-geolocation-jquery/</link>
		<comments>http://tutorialzine.com/2012/05/weather-forecast-geolocation-jquery/#comments</comments>
		<pubDate>Mon, 14 May 2012 09:13:18 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1985</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2012/05/weather-forecast-geolocation-jquery/"><img src="http://cdn.tutorialzine.com/img/featured/1985.jpg" /></a></div> Today we will be using the HTML5 Geolocation API to present the user with a personalized weather forecast.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2012/05/weather-forecast-geolocation-jquery/"><img src="http://cdn.tutorialzine.com/img/featured/1985.jpg" /></a></div> <p>Today we will be using the HTML5 geolocation API to present the user with a personalized weather forecast. Using jQuery, we will issue AJAX request to two of Yahoo&#8217;s popular APIs to obtain additional geographical information and a weather forecast. This example also makes use of the wonderful <a href="http://adamwhitcroft.com/climacons/" target="_blank">climacons icon set</a>.</p>
<h3>Obtaining an Application Key</h3>
<p>Yahoo provides a <a href="http://developer.yahoo.com/everything.html" target="_blank">large collection of useful APIs</a> that are free for developers to use. The requirement is that you register your application with through their <a href="https://developer.apps.yahoo.com/dashboard/createKey.html" target="_blank">developer dashboard</a>. The registration is simple and straightforward, and as a result you obtain an application id (look for it under the title of your application). You are going to need this later in the tutorial, but first let&#8217;s see how everything would work together.</p>
<h3>The Idea</h3>
<p>Here is what we need to do in order to display our weather forecast:</p>
<ul>
<li>First we&#8217;ll use the <em>Geolocation API</em> supported by modern browsers. The API will prompt the user to authorize location access and will return a set of GPS coordinates;</li>
<li>Next, we will issue a request to Yahoo&#8217;s <a href="http://developer.yahoo.com/geo/placefinder/" target="_blank">PlaceFinder API</a>, passing the above coordinates. This will give us the name of the city and country, and a <strong>woeid</strong> &#8211; a special ID used to identify the city in weather forecasts;</li>
<li>Finally, we will issue a request to Yahoo&#8217;s <a href="http://developer.yahoo.com/weather/" target="_blank">Weather API</a> with that woeid. This will give us current weather conditions, as well as a forecast for the rest of the current and the next day.</li>
</ul>
<p>Great! We are now ready for the HTML.</p>
<div id="attachment_1996" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2012/05/weather-forecast-geolocation-jquery/"><img class="size-full wp-image-1996" title="Weather Forecast Web App" src="http://cdn.tutorialzine.com/wp-content/uploads/2012/05/jquery-geolocation-weather-app.jpg" alt="Weather Forecast Web App" width="620" height="460" /></a><p class="wp-caption-text">Weather Forecast Web App</p></div>
<h3>The HTML</h3>
<p>We will start with a blank HTML5 document, and we will add a reference to our stylesheet to the head section, along with two fonts from <a href="http://www.google.com/webfonts" target="_blank">Google&#8217;s Webfonts</a> library. In the body we will add a h1 header and markup for the weather forecast slider.</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;Weather Forecast with jQuery &amp;amp; Yahoo APIs | Tutorialzine Demo&lt;/title&gt;

        &lt;!-- The stylesheet --&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=Playball|Open+Sans+Condensed:300,700" /&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;Weather Forecast&lt;/h1&gt;
		&lt;/header&gt;

        &lt;div id="weather"&gt;

        	&lt;ul id="scroller"&gt;
        		&lt;!-- The forecast items will go here --&gt;
        	&lt;/ul&gt;

        	&lt;a href="#" class="arrow previous"&gt;Previous&lt;/a&gt;
        	&lt;a href="#" class="arrow next"&gt;Next&lt;/a&gt;

        &lt;/div&gt;

        &lt;p class="location"&gt;&lt;/p&gt;

        &lt;div id="clouds"&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.2.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>Before the closing body tag we are adding the latest version of jQuery and our script.js file, which we are discussing in the following sections.</p>
<h3>The JavaScript</h3>
<p>The first step is to define two configuration variables in <strong>/assets/js/script.js</strong>:</p>
<pre class="brush:js">var APPID = '';	// Your Yahoo Application ID
var DEG = 'c';	// c for celsius, f for fahrenheit</pre>
<p>These are passed as parameters with the AJAX requests for the location and weather APIs as you will see in a moment.</p>
<p>Following the outline in the idea section, we should now look into using the <em>HTML5 Geolocation API</em> to obtain a set of GPS coordinates. This API is supported by all new browsers including IE9 and mobile devices. To use it, we need to test whether the global navigator object has a <strong>geolocation</strong> property. If it does, we call its <strong>getCurrentPosition</strong> method passing two event handling functions for success and failure. Here is the relevant code from <strong>script.js</strong> that does this:</p>
<pre class="brush:js">// Does this browser support geolocation?
if (navigator.geolocation) {
	navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
}
else{
	showError("Your browser does not support Geolocation!");
}

function locationSuccess(position) {
	var lat = position.coords.latitude;
	var lon = position.coords.longitude;

	// We will make further requests to Yahoo's APIs here
}

function locationError(error){
	switch(error.code) {
		case error.TIMEOUT:
			showError("A timeout occured! Please try again!");
			break;
		case error.POSITION_UNAVAILABLE:
			showError('We can\'t detect your location. Sorry!');
			break;
		case error.PERMISSION_DENIED:
			showError('Please allow geolocation access for this to work.');
			break;
		case error.UNKNOWN_ERROR:
			showError('An unknown error occured!');
			break;
	}

}

function showError(msg){
	weatherDiv.addClass('error').html(msg);
}</pre>
<p>The <strong>locationSuccess</strong> function is where we will be issuing requests to Yahoo&#8217;s APIs in a moment. The <strong>locationError</strong> function is passed an error object with the specific reason for the error condition. We will use a <strong>showError</strong> helper function to display the error messages on the screen.</p>
<p>The full version of <em>locationSuccess</em> follows:</p>
<pre class="brush:js">function locationSuccess(position) {
	var lat = position.coords.latitude;
	var lon = position.coords.longitude;

	// Yahoo's PlaceFinder API http://developer.yahoo.com/geo/placefinder/
	// We are passing the R gflag for reverse geocoding (coordinates to place name)
	var geoAPI = 'http://where.yahooapis.com/geocode?location='+lat+','+lon+'&amp;flags=J&amp;gflags=R&amp;appid='+APPID;

	// Forming the query for Yahoo's weather forecasting API with YQL
	// http://developer.yahoo.com/weather/

	var wsql = 'select * from weather.forecast where woeid=WID and u="'+DEG+'"',
		weatherYQL = 'http://query.yahooapis.com/v1/public/yql?q='+encodeURIComponent(wsql)+'&amp;format=json&amp;callback=?',
		code, city, results, woeid;

	// Issue a cross-domain AJAX request (CORS) to the GEO service.
	// Not supported in Opera and IE.
	$.getJSON(geoAPI, function(r){

		if(r.ResultSet.Found == 1){

			results = r.ResultSet.Results;
			city = results[0].city;
			code = results[0].statecode || results[0].countrycode;

			// This is the city identifier for the weather API
			woeid = results[0].woeid;

			// Make a weather API request (it is JSONP, so CORS is not an issue):
			$.getJSON(weatherYQL.replace('WID',woeid), function(r){

				if(r.query.count == 1){

					// Create the weather items in the #scroller UL

					var item = r.query.results.channel.item.condition;
					addWeather(item.code, "Now", item.text + ' &lt;b&gt;'+item.temp+'°'+DEG+'&lt;/b&gt;');

					for (var i=0;i&lt;2;i++){
						item = r.query.results.channel.item.forecast[i];
						addWeather(
							item.code,
							item.day +' &lt;b&gt;'+item.date.replace('\d+$','')+'&lt;/b&gt;',
							item.text + ' &lt;b&gt;'+item.low+'°'+DEG+' / '+item.high+'°'+DEG+'&lt;/b&gt;'
						);
					}

					// Add the location to the page
					location.html(city+', &lt;b&gt;'+code+'&lt;/b&gt;');

					weatherDiv.addClass('loaded');

					// Set the slider to the first slide
					showSlide(0);

				}
				else {
					showError("Error retrieving weather data!");
				}
			});

		}

	}).error(function(){
		showError("Your browser does not support CORS requests!");
	});

}</pre>
<p>The PlaceFinder API returns its results as plain JSON. But as it is on a different domain, only browsers that support CORS (cross origin resource sharing) will be able to retrieve it. Most major browsers that support geolocation also support CORS, with the exception of IE9 and Opera, which means that this example won&#8217;t work there.</p>
<p>Another thing to consider is that the weather API returns only two days of forecasts, which somewhat limits the utility of our web app, but unfortunately there is no way around it.</p>
<blockquote class="note"><p>We are only using the Weather API for temperature data, but it provides additional information that you might find useful. You can play with the API and browse the responses in the <a href="http://developer.yahoo.com/yql/console/?q=show%20tables&amp;env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20weather.forecast%20where%20woeid%3D2502265" target="_blank">YQL console</a>.</p></blockquote>
<p>After we retrieve the weather data, we call the <strong>addWeather</strong> function, which creates a new LI item in the <em>#scroller</em> unordered list.</p>
<pre class="brush:js">function addWeather(code, day, condition){

	var markup = '&lt;li&gt;'+
		'&lt;img src="assets/img/icons/'+ weatherIconMap[code] +'.png" /&gt;'+
		' &lt;p class="day"&gt;'+ day +'&lt;/p&gt; &lt;p class="cond"&gt;'+ condition +
		'&lt;/p&gt;&lt;/li&gt;';

	scroller.append(markup);
}</pre>
<p>Now we need to listen for clicks on the previous / next arrows, so we can offset the slider to reveal the correct day of the forecast.</p>
<pre class="brush:js">	/* Handling the previous / next arrows */

	var currentSlide = 0;
	weatherDiv.find('a.previous').click(function(e){
		e.preventDefault();
		showSlide(currentSlide-1);
	});

	weatherDiv.find('a.next').click(function(e){
		e.preventDefault();
		showSlide(currentSlide+1);
	});

	function showSlide(i){
		var items = scroller.find('li');

		// Exit if the requested item does not exist,
		// or the scroller is currently being animated
		if (i &gt;= items.length || i &lt; 0 || scroller.is(':animated')){
			return false;
		}

		// The first/last classes hide the left/right arrow with CSS
		weatherDiv.removeClass('first last');

		if(i == 0){
			weatherDiv.addClass('first');
		}
		else if (i == items.length-1){
			weatherDiv.addClass('last');
		}

		scroller.animate({left:(-i*100)+'%'}, function(){
			currentSlide = i;
		});
	}</pre>
<p><strong>With this our simple weather web app is complete!</strong> You can see everything together in <em>/assets/js/script.js</em>. We won't be discussing the styling here, but you can read through <em>/assets/css/styles.css</em> yourself.</p>
<h3>Done!</h3>
<p>In this example you learned how to use the HTML5 geolocation with Yahoo's Weather and Places APIs to present a location-aware weather forecast. It works on most modern web browsers and mobile devices.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2012/05/weather-forecast-geolocation-jquery/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<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>Enhance Your Website with the FullScreen API</title>
		<link>http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/</link>
		<comments>http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/#comments</comments>
		<pubDate>Mon, 06 Feb 2012 08:49:42 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1821</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/"><img src="http://cdn.tutorialzine.com/img/featured/1821.jpg" /></a></div> There is a new API in town - Full Screen. With it you can make any element take the entire screen. Perfect for videos and canvas-based games, reports and print preview dialogs. Learn how to use it in this tutorial.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/"><img src="http://cdn.tutorialzine.com/img/featured/1821.jpg" /></a></div> <p>One of the benefits to having new browser versions out every six weeks, is the rapid pace with which new functionality is introduced. The transition from nightly builds to official releases is merely weeks away. This means that even those of you who keep a close eye on the feature lists might miss an api or two.</p>
<p>This is the case with the <a href="https://developer.mozilla.org/en/DOM/Using_full-screen_mode" target="_blank">Full Screen API</a>. As if overnight, it went from a neat experiment to a feature supported by more than half of the browsers in the wild. Right now you might be wondering how is this different from the regular full screen we&#8217;ve had for ages.</p>
<h3>What you need to know</h3>
<p>With this api, you can display not only entire pages full screen, but individual elements within them as well (something you can&#8217;t do with the regular full screen). The intent here is to allow for full screen HTML5 videos and games, so that we can finally declare HTML5 as a viable alternative to Flash.</p>
<p>In short, here is what you need to know about the FullScreen API:</p>
<ul>
<li>Works in <em>Firefox 10</em>, <em>Safari</em> and <em>Chrome</em>;</li>
<li>You trigger it using the new <code>requestFullScreen()</code> method;</li>
<li>It can display any element full screen, not only the entire page;</li>
<li>For security reasons, full screen can only be triggered from an event handler (as to be user initiated);</li>
<li>Also for security, Safari blocks all keyboard input except for the arrows and control keys, other browsers show warning messages when typing;</li>
<li>The API is still a work in progress, so you have to use the vendor specific methods (prefixed with <strong>moz</strong> and <strong>webkit</strong>);</li>
</ul>
<p>The idea of allowing developers to programatically take up the user screen doesn&#8217;t come without serious security implications, which is why keyboard usage is limited. Of course, there are many legitimate uses for keyboard input in full screen, which is going to be addressed in future revisions of the API via some kind of permission prompt.</p>
<p>However, even in its current, limited form, the API still gives us an opportunity to enhance the experience of the end user.</p>
<div id="attachment_1841" class="wp-caption alignnone" style="width: 630px"><a href="http://cdn.tutorialzine.com/wp-content/uploads/2012/02/click-to-go-full-screen.jpg"><img class="size-full wp-image-1841" title="Click to go Full Screen" src="http://cdn.tutorialzine.com/wp-content/uploads/2012/02/click-to-go-full-screen.jpg" alt="Click to go Full Screen" width="620" height="260" /></a><p class="wp-caption-text">Click to go Full Screen</p></div>
<h3>The basics</h3>
<p>According to the <a href="http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html" target="_blank">W3 draft</a>, we have access to a number of methods and properties that will aid us with the task of switching an element to full screen.</p>
<pre class="brush:js">var elem = document.getElementById('#content');

// Make this element full screen asynchronously
elem.requestFullscreen();

// When a full screen change is detected,
// an event will be dispatched on the document

document.addEventListener("fullscreenchange",function(){
    // Check if we are in full screen
    if(document.fullscreen)){
        // We are now in full screen!
    }
    else{
        // We have exited full screen mode
    }

}, false);

// We can also exit the full screen mode with code

document.exitFullscreen();</pre>
<p>At this time, however, dealing with the API is quite more cumbersome, as no browser has support for these methods yet &#8211; we will need to use <a href="http://hacks.mozilla.org/2012/01/using-the-fullscreen-api-in-web-browsers/" target="_blank">vendor specific ones</a> like <code>elem.mozRequestFullScreen()</code> and <code>elem.webkitRequestFullScreen()</code>.</p>
<p>The API also introduces a new CSS pseudo-selector that you can use to style the full screen element.</p>
<pre class="brush:css">#content:fullscreen {
    font-size: 18;
}</pre>
<p>Of course, it goes without saying that you will also need to supply moz and webkit prefixed versions of this as well. But there is an easier solution.</p>
<h3>The jQuery plugin</h3>
<p>There is a more elegant solution than ending up with a bunch of ugly code checking for every browser. You can use the <a href="https://github.com/martinaglv/jQuery-FullScreen" target="_blank">jQuery FullScreen plugin,</a> which works around various browser differences and gives you a simple method for triggering full screen mode.</p>
<pre class="brush:js">$('#fsButton').click(function(e){
    // Use the plugin
    $('#content').fullScreen();
    e.preventDefault();
});</pre>
<p>This will bring the #content element full screen. The plugin also adds a flag to the jQuery support object, so you can conditionally show your full screen button or trigger:</p>
<pre class="brush:js">if($.support.fullscreen){
    // Show the full screen button
    $('#fsButton').show();
}</pre>
<p>To exit the mode, call the fullScreen() method again.</p>
<p>The plugin adds the .fullScreen class to your element, so you can style it without needing to worry about browser-specific versions. Now let&#8217;s use it to do some good for the world!</p>
<h3>The fun part</h3>
<p>If you are a website owner you&#8217;ve probably made decisions that deteriorate the experience of your users. This should not come as a surprise to you &#8211; you need to show advertising, you need a search box, a navigation bar, a twitter widget, a comment section and all the things that make your site what it is. These are all necessary, but make your content, the very thing that people came to your site for, more difficult to read.</p>
<p>There is also a practical limit to how large your font can be before it gets out of place, not to mention the choice of a type face. If you have a sidebar, this also limits the horizontal space your content can take.</p>
<p>But we can fix this with the new API. We will use the functionality to bring the content section of your site full screen, thus improving the reading experience of your readers even on devices with small displays like laptops and netbooks.</p>
<div id="attachment_1840" class="wp-caption alignnone" style="width: 630px"><img class="size-full wp-image-1840" title="Reader Mode Using the Full Screen API" src="http://cdn.tutorialzine.com/wp-content/uploads/2012/02/reader-mode-full-screen-api.jpg" alt="Reader Mode Using the Full Screen API" width="620" height="460" /><p class="wp-caption-text">Reader Mode Using the Full Screen API</p></div>
<h4>Making the reading mode</h4>
<p>It is pretty straightforward, we only need to some kind of button that will trigger the FullScreen plugin. We can use the <strong>$.support.fullscreen</strong> flag to test if the current browser supports the API. If it does, we will add the full screen button to the page.</p>
<pre class="brush:js">if($.support.fullscreen){

	var fullScreenButton = $('&lt;a class="goFullScreen"&gt;').appendTo('#buttonStrip');

	fullScreenButton.click(function(e){
		e.preventDefault();
		$('#main').fullScreen();
	});
}</pre>
<p>When the <span style="text-decoration: underline;">#main</span> div is brought full screen, it is assigned a width and height of 100%. We will have to work around this if we want it centered in the middle of the screen. This will call for some additional styling, applied only in full screen mode.</p>
<pre class="brush:css">a.goFullScreen{
	/* The styling of the full screen button goes here */
}

/* The following styles are applied only in Full Screen mode */

#main.fullScreen{
	/* Adding a width and margin:0 auto to center the container */
	width: 860px;
	margin: 0 auto;

	/* Increasing the font size for legibility*/
	font: 17px serif;
	padding: 45px 45px 10px;
}

#main.fullScreen h1{
	/* Styling the heading */
	font: 56px/1.1 Cambria,"Palatino Linotype",serif;
	text-align: center;
}

#main.fullScreen h3{
	/* Subheadings */
	font: 28px Cambria,"Palatino Linotype",serif;
}

#main.fullScreen #postAuthor{
	/* Centering the post author info */
	/* ... */
}

/* Hiding unneeded elements and ads */

#main.fullScreen #featuredImage,
#main.fullScreen #topMiniShare,
#main.fullScreen #wideZineBanner,
#main.fullScreen #downloadDemo{
	display:none;
}</pre>
<p>That is all there is to it! Only browsers that support full screen mode will display the button and users will enjoy a better, distraction-free reading experience.</p>
<h3><strong></strong>Done!</h3>
<p>There are plenty of places in a website where you can use a full screen view &#8211; from videos and canvas-based games, to reports and print preview dialogs. I would personally love to see this used for infographics and presentations. We can go a long way with a useful feature like this.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/feed/</wfw:commentRss>
		<slash:comments>27</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>How to Block Adblock</title>
		<link>http://tutorialzine.com/2011/12/how-to-block-adblock/</link>
		<comments>http://tutorialzine.com/2011/12/how-to-block-adblock/#comments</comments>
		<pubDate>Fri, 16 Dec 2011 17:43:10 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1751</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2011/12/how-to-block-adblock/"><img src="http://cdn.tutorialzine.com/img/featured/1751.jpg" /></a></div> Today we will give website owners a chance and write a plugin with which they can detect whether a visitor is using an ad blocker.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2011/12/how-to-block-adblock/"><img src="http://cdn.tutorialzine.com/img/featured/1751.jpg" /></a></div> <p>If you are a website owner, there is a pretty good chance that you rely on some form of advertising to pay for your hosting bills. And if you are lucky enough to have more than a few people visiting your site, you might even be able to pay yourself a supplement to your salary as a compensation for your hard work.</p>
<p>On the other side there are the people that browse the web. They are tired of being bombarded with intrusive advertising, flashy banners and announcements that ruin their browsing experience. They don&#8217;t need to be congratulated on being the millionth visitor of your website, they don&#8217;t want to shoot five iphones, their only wish is to read what you have to say.</p>
<p>As it is much easier for users to hide ads than for the entire industry to develop advertising ethics, a simple solution quickly emerged.</p>
<h3>Then Came Adblockers</h3>
<p>The idea of an adblocker is simple &#8211; it is a browser extension that blocks or removes advertising on the page. A &#8220;solution&#8221; is hardly the proper term, however, as it only serves one side &#8211; the users. There frankly couldn&#8217;t be a better deal for them. These extensions strip everything except the main content of the page, bringing a whole new dimension to the word free &#8211; it not only means that they don&#8217;t pay; it now means that you don&#8217;t get paid too!</p>
<div id="attachment_1754" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/12/how-to-block-adblock/"><img class="size-full wp-image-1754" title="Adblocker detected!" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/12/adblocker-detected.jpg" alt="Adblocker detected!" width="620" height="460" /></a><p class="wp-caption-text">Adblocker detected!</p></div>
<p>This didn&#8217;t use to be a big of a problem for website owners &#8211; people using ad blockers weren&#8217;t that many, and it did make users enjoy browsing your site more. But as the idea for browser extensions exploded in recent years, so did the proliferation of ad blockers. A quick look at the <a href="https://addons.mozilla.org/en-US/firefox/extensions/?sort=users" target="_blank">addon</a> <a href="https://chrome.google.com/webstore/category/popular" target="_blank">directories</a> reveals that ad blockers are the most popular category.</p>
<p>Small sites are most at risk, as they can&#8217;t attract the same interest from advertisers and experiment with different formats. With more than 20% of pageviews eaten away by adblockers (these are the number for Tutorialzine), it becomes evident that something has to change.</p>
<p>Miraculously, in the past few weeks there were news that the most popular ad blocker &#8211; AdBlock Plus <a href="https://adblockplus.org/en/acceptable-ads" target="_blank">will start allowing acceptable advertising by default</a>. Judging by the uproar this decision brought, a large percentage of people will still opt in for complete blocking of ads or move to a different extension. This means that we as publishers will still have to maneuver around this problem for some time to come. One solution would be to detect the presence of an ad blocker.</p>
<h3>How To Detect AdBlock</h3>
<p>It is simple &#8211; we will use ad blockers&#8217; overzealous interference against it. To block ads such an extension must look for files it believes contain code that shows adverts and prevent them from loading. So the idea is to have a JS file named <strong>advertisement.js</strong>, which will trigger adblock&#8217;s filters, and after this, check whether the file has been loaded.</p>
<p>Here is the file itself:</p>
<h4>assets/blockBlock/advertisement.js</h4>
<pre class="brush:js">jQuery.adblock = false;</pre>
<p>That&#8217;s all, one line. It creates a new property on the global jQuery object, which we will later look for. If it is undefined, it would mean that this file has been blocked from loading.</p>
<h4>assets/blockBlock/blockBlock.jquery.js</h4>
<pre class="brush:js">(function($){

	if ($.adblock === undefined){
		$.adblock = true;
	}

	$.fn.showOnAdBlock = function(){

		if($.adblock){
			this.show();
		}

		return this;
	};

})(jQuery);</pre>
<p>To find out if an ad blocker is present, simply do a conditional check for the $.adblock variable. In the same file, we also define a helper method that will conditionally show an element depending if such an extension is active.</p>
<p><strong>Update:</strong> This plugin is also <a href="https://github.com/martinaglv/BlockBlock" target="_blank">available on Github</a>.</p>
<p>When including the plugin in your site, remember to include the files above <strong>after</strong> the jQuery library. For the demo page I am also using the <a href="http://tutorialzine.com/2010/12/better-confirm-box-jquery-css3/">confirm dialog replacement</a> from last year to show a pretty dialog box informing the users they should disable adblock to view the page. Here is the code for that:</p>
<h4>assets/js/script.js</h4>
<pre class="brush:js">$(function(){

	if($.adblock){
		$.confirm({
			'title'		: 'Adblocker active!',
			'message'	: 'You are running an ..',
			'buttons'	: {
				'I will!'	: {
					'class'	: 'blue',
					'action': function(){
						// Do nothing
						return;
					}
				},
				'Never!'	: {
					'class'	: 'gray',
					'action': function(){
						// Redirect to some page
						window.location = 'http://tutorialzine.com/';
					}
				}
			}
		});
	}
});</pre>
<p>Bang! Now you can tell who is using an ad blocker. This simple method works with most of the popular ad cleaning plugins used at the moment.</p>
<h3>What to use it for?</h3>
<p>Okay, so you have a snippet of code that would tell you if a person is using an ad blocker or not. What to do now? Some ideas follow. I would not personally use any of the bad or evil ones, but I am obliged to share.</p>
<h4>Good ideas</h4>
<ul>
<li>Track how many people are blocking ads on your website. If the percentage is high, you can try different (non-banner) types of advertisement;</li>
<li>Replace the areas of your website where ads usually go with some useful content;</li>
<li>Inform visitors how adblock harms small websites with a heartbreaking personal appeal ala Jimmy Wales.</li>
</ul>
<h4>Bad ideas</h4>
<ul>
<li>Show a big message that adblocked users are not welcome (like in the demo);</li>
<li>Beg for donations;</li>
<li>Replace with ads for affiliate programs that are not blocked by the extension.</li>
</ul>
<h4>Outright evil ideas</h4>
<ul>
<li>Set up a paywall for adblocked users;</li>
<li>Require a sign-in with facebook or a registration;</li>
<li>Redirect to a daily deal website with your affiliate link.</li>
</ul>
<h3>A bright future?</h3>
<p>Hopefully the initiative behind AdBlock Plus&#8217; decision to show non-intrusive ads resonates in the community and we will enjoy advertising that is accepted and useful for both publishers and visitors.</p>
<p><strong>What are your thoughts about AdBlock?</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/12/how-to-block-adblock/feed/</wfw:commentRss>
		<slash:comments>45</slash:comments>
		</item>
		<item>
		<title>What You Need To Know About The HTML5 Slider Element</title>
		<link>http://tutorialzine.com/2011/12/what-you-need-to-know-html5-range-input/</link>
		<comments>http://tutorialzine.com/2011/12/what-you-need-to-know-html5-range-input/#comments</comments>
		<pubDate>Fri, 09 Dec 2011 16:26:38 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1722</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2011/12/what-you-need-to-know-html5-range-input/"><img src="http://cdn.tutorialzine.com/img/featured/1722.jpg" /></a></div> The new HTML5 slider control is useful for giving users the ability to conveniently modify a value without having to explicitly type it in a text box. In this short tutorial you will learn how to use it and how to emulate it in older browsers.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2011/12/what-you-need-to-know-html5-range-input/"><img src="http://cdn.tutorialzine.com/img/featured/1722.jpg" /></a></div> <p>HTML5 brought a lot of new tags and new rules on how the old ones should be used. One of them is the range input element, or the slider. This control has been available in operating systems for decades, but is only now that it has found its way into the browser.</p>
<p>The reason for this delay is probably that it is easy to emulate the functionality with JavaScript alone. The jQuery UI library includes a <a href="http://jqueryui.com/demos/slider/" target="_blank">pretty capable version</a> that is also easy to style. But having it built into the browser and ready to go is much more convenient, at least for the browsers that support it.</p>
<div id="attachment_1733" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/12/what-you-need-to-know-html5-range-input/"><img class="size-full wp-image-1733 " title="The Slider Element in Google Chrome" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/12/chrome-range-input-slider-element.jpg" alt="The Slider Element in Google Chrome" width="620" height="260" /></a><p class="wp-caption-text">20 years in the making, but we finally have it!</p></div>
<h3>Browser support</h3>
<p>All modern browsers support this element with the notable <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=344618" target="_blank">exception of Firefox</a>, but it can be easily recreated with <a href="http://frankyan.com/labs/html5slider/" target="_blank">html5slider.js</a>. Of course IE also does not support the range input (no surprise here), for which there are no easy fixes. This means that to use it cross-browser you will still need to include a separate enabling library like jQuery UI (more on that later on). The good thing is that even if the browser does not support the range element, it will fall back to a textbox.</p>
<div id="attachment_1734" class="wp-caption alignnone" style="width: 630px"><img class="size-full wp-image-1734" title="Browser support could be better." src="http://cdn.tutorialzine.com/wp-content/uploads/2011/12/browser-support.jpg" alt="Browser support for the range input" width="620" height="260" /><p class="wp-caption-text">Browser support for the range input</p></div>
<h3>How it works</h3>
<p>I referred to the slider as &#8220;range input&#8221; for a reason. It is a type of input element, rather than a separate tag &#8211; <code>&lt;input type="range" /&gt;</code> is all you need to display it in your page. It supports the regular <strong>value</strong> attribute shared by all input elements, along with <strong>min</strong> and <strong>max</strong>, which limit the range, and <strong>step</strong> which sets how much the value changes on every movement (default is 1).</p>
<table cellspacing="0" cellpadding="0">
<caption>Supported attributes by &lt;input type=&#8221;range&#8221; /&gt;</caption>
<tbody>
<tr>
<th>Attribute</th>
<th>Value</th>
<th>Default</th>
<th>Description</th>
</tr>
<tr>
<td>value</td>
<td>number</td>
<td>not set</td>
<td>The default position of the slider.</td>
</tr>
<tr>
<td>min</td>
<td>number</td>
<td>0</td>
<td>The bottom limit of the range. This is the value of the input when the slider is on the leftmost position.</td>
</tr>
<tr>
<td>max</td>
<td>number</td>
<td>100</td>
<td>The top limit of the range. This is the value of the input when the slider is on the rightmost position.</td>
</tr>
<tr>
<td>step</td>
<td>number</td>
<td>1</td>
<td>The amount with which the value changes on each movement of the slider.</td>
</tr>
</tbody>
</table>
<p>You can change these attributes with JavaScript/jQuery as you would with any regular input element. You can also use the onchange event to listen for changes. This is what the code looks like:</p>
<h4>Extracted from index.html</h4>
<pre class="brush:html">&lt;input id="defaultSlider" type="range" min="0" max="500" /&gt;
&lt;p class="note"&gt;Current value: &lt;span id="currentValue"&gt;0&lt;/span&gt;&lt;/p&gt;</pre>
<p>And this is the jQuery code that listens for the change event:</p>
<h4>assets/js/slider-default.js</h4>
<pre class="brush:js">$(function(){

	var currentValue = $('#currentValue');

	$('#defaultSlider').change(function(){
	    currentValue.html(this.value);
	});

	// Trigger the event on load, so
	// the value field is populated:

	$('#defaultSlider').change();

});</pre>
<p>Of course this code will only work if your browser supports the slider element. Otherwise you will be presented with a textbox.</p>
<h3>Lets level the field</h3>
<p>As more than two thirds of the internet population won&#8217;t be able to see our pretty slider, we need to take a different path. Lets build a quick and dirty version of the slider using <a href="http://jqueryui.com/demos/slider/" target="_blank">jQuery UI</a>, a library of interface components that sits on top of jQuery.</p>
<h4>Extracted from slider-jqueryui.html</h4>
<pre class="brush:html">&lt;div id="slider"&gt;&lt;/div&gt;
&lt;p class="note"&gt;Current value: &lt;span id="currentValue"&gt;0&lt;/span&gt;&lt;/p&gt;</pre>
<p>You can see the code for the jQuery UI Slider control below (you need to include jQuery UI alongside jQuery in your page).</p>
<h4>assets/js/slider-jqueryui.js</h4>
<pre class="brush:js">$(function(){

	var currentValue = $('#currentValue');

	$("#slider").slider({
		max: 500,
		min: 0,
		slide: function(event, ui) {
			currentValue.html(ui.value);
		}
	});

});</pre>
<p>The code is pretty straightforward. It simply uses the slider method and the library does the rest.</p>
<h3>The fun part</h3>
<p>Here comes a realization &#8211; as we are already presenting our own custom version of the slider, we can as well present an entirely different control. Lets use the <a title="Shiny Knob Control with jQuery and CSS3" href="http://tutorialzine.com/2011/11/pretty-switches-css3-jquery/" target="_blank">KnobKnob plugin</a> from last week.</p>
<p>We will have the range input control on the page, but it will be hidden. KnobKnob will then create a rotating control that will have the same limits as the original slider. On every change we will update the value of the hidden slider:</p>
<h4>slider-knob.html</h4>
<pre class="brush:html">&lt;div id="container"&gt;
	&lt;div id="control"&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;!-- The range input is hidden and updated on each rotation of the knob --&gt;
&lt;input type="range" id="slider" min="0" max="500" value="25" /&gt;

&lt;p class="note"&gt;Current value: &lt;span id="currentValue"&gt;0&lt;/span&gt;&lt;/p&gt;</pre>
<p>And for the jQuery part:</p>
<h4>assets/js/slider-knob.js</h4>
<pre class="brush:js">$(function(){

	var slider = $('#slider'),
		min = slider.attr('min'),
		max = slider.attr('max'),
		currentValue = $('#currentValue');

	// Hiding the slider:
	slider.hide();

	$('#control').knobKnob({
		snap : 10,
		value: 250,
		turn : function(ratio){
			// Changing the value of the hidden slider
			slider.val(Math.round(ratio*(max-min) + min));

			// Updating the current value text
			currentValue.html(slider.val());
		}
	});

});</pre>
<p>The code above takes the min and max attributes of the range input and uses it to calculate the corresponding value of the slider.</p>
<h3>Conclusion</h3>
<p>The slider control is useful for giving users the ability to conveniently modify a value without having to explicitly type it in a text box. Although there is much to be desired in terms of browser support, you can use progressive enhancement to display an alternative control using jQuery.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/12/what-you-need-to-know-html5-range-input/feed/</wfw:commentRss>
		<slash:comments>8</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>
	</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 707/732 objects using apc
Content Delivery Network via cdn.tutorialzine.com

Served from: tutorialzine.com @ 2012-05-21 03:25:36 -->
