<?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, 06 Feb 2012 08:49:42 +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>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>10</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>38</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>36</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>28</slash:comments>
		</item>
		<item>
		<title>Chained AJAX Selects</title>
		<link>http://tutorialzine.com/2011/11/chained-ajax-selects-jquery/</link>
		<comments>http://tutorialzine.com/2011/11/chained-ajax-selects-jquery/#comments</comments>
		<pubDate>Thu, 03 Nov 2011 15:40:06 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[PHP]]></category>

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

	var questions = $('#questions');

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

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

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

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

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

			if(connection){
				fetchSelect(connection);
			}

		});
	}

	var working = false;

	function fetchSelect(val){

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

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

			var connection, options = '';

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

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

			if(r.defaultText){

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

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

			// Building the markup for the select section

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

			refreshSelects();

			working = false;
		});

	}

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

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

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

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

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

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

// Product selectbox

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

// Phone types

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

// Smartphones

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

// Feature phones

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

// iPhone colors

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

// Notebook select

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

// Tablet select

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

// Case select

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

// Register all the select items in an array

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

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

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

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

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

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

    &lt;body&gt;

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

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

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

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

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

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

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

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

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

	function createImage(file){

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

		var reader = new FileReader();

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

		reader.onload = function(e){

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	});

	var template = '...'; 

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

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

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

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

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

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

	$pic = $_FILES['pic'];

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

	if($demo_mode){

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

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

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

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

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

}

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

// Helper functions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#dropbox .preview.done .progress{
	width:100% !important;
}</pre>
<p>The <em>.progress</em> div is positioned absolutely. Changing its width (in percent) makes for a natural progress indicator. Throw in a 0.25 transition, and you have animated increments which would be a bit tricky to do with jQuery alone.</p>
<p><strong>With this our HTML5 Upload Center is complete!</strong></p>
<h3>We&#8217;re done!</h3>
<p>You can use this as a starting point for a file upload service, HTML5 gallery, file manager or your app&#8217;s new admin panel. Add your thoughts or suggestions in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/feed/</wfw:commentRss>
		<slash:comments>62</slash:comments>
		</item>
		<item>
		<title>jQuery PointPoint &#8211; A Plugin For Pointing To Things</title>
		<link>http://tutorialzine.com/2011/09/jquery-pointpoint-plugin/</link>
		<comments>http://tutorialzine.com/2011/09/jquery-pointpoint-plugin/#comments</comments>
		<pubDate>Mon, 12 Sep 2011 14:08:10 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1609</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2011/09/jquery-pointpoint-plugin/"><img src="http://cdn.tutorialzine.com/img/featured/1609.jpg" /></a></div> In this tutorial, we will be writing a jQuery plugin that will help you draw users' attention to a specific part of the page, in the form of a small arrow that is displayed next to their mouse cursor.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2011/09/jquery-pointpoint-plugin/"><img src="http://cdn.tutorialzine.com/img/featured/1609.jpg" /></a></div> <p>Web designers find themselves in a tough situation &#8211; they have to build beautiful user interfaces that are intuitive and usable in the same time. Sometimes, despite our earnest efforts, web applications may become difficult to use for novice users. One solution is to create some sort of a tour of your application&#8217;s features. The other is to incorporate visual cues in the design itself.</p>
<p>In this tutorial, we will be writing a jQuery plugin that will help you draw users&#8217; attention to a specific part of the page, in the form of a small arrow that is displayed next to their mouse cursor. This can be useful for pointing to missed form fields, buttons that need to be pressed, or validation errors that need to be scrolled into view.</p>
<h3>How it works</h3>
<p>Lets dive straight to the code &#8211; it comes at around 100 lines (with comments), so it is not difficult to follow.</p>
<h4>jquery.pointpoint.js</h4>
<pre class="brush:js">(function($){

	// Defining our jQuery plugin

	$.fn.pointPoint = function(prop){

		// Default parameters

		var options = $.extend({
			"class"		: "pointPointArrow",
			"distance"	: 30
		},prop);

		var pointers = [];

		// If CSS transforms are not supported, exit;

		if(!$.support.transform){
			this.destroyPointPoint = function(){};
			return this;
		}

		this.each(function(){

			var findMe = $(this),
				point = $('&lt;div class="'+options['class']+'"&gt;').appendTo('body'),
				offset, center = {}, mouse = {}, props = {}, a, b, h, deg, op,
				pointHidden = true, rad_to_deg = 180/Math.PI;

			pointers.push(point);

			// Calculating the position of the pointer on mouse move

			$('html').bind('mousemove.pointPoint',function(e){

				if(pointHidden){
					point.show();
					pointHidden = false;
				}

				offset = findMe.offset();

				// The center of the element we are pointing at
				center.x = offset.left + findMe.outerWidth()/2;
				center.y = offset.top + findMe.outerHeight()/2;

				mouse.x = e.pageX;
				mouse.y = e.pageY;

				// We are treating the mouse position and center
				// point as the corners of a right triangle.
				// h is the hypotenuse, or distance between the two.

				a = mouse.y - center.y;
				b = center.x - mouse.x;
				h = Math.sqrt(a*a + b*b);

				// Calculating the degree (in radians),
				// the pointer should be rotated by:
				deg = Math.atan2(a,b);

				// Lowering the opacity of the pointer, depending
				// on the distance from the mouse pointer

				op = 1;
				if(h &lt; 50){
					op = 0;
				} else if(h &lt; 160){
					op = (h - 50) / 110;
				}

				// Moving and rotating the pointer

				props.marginTop  = mouse.y-options.distance*Math.sin(deg);
				props.marginLeft = mouse.x+options.distance*Math.cos(deg);
				props.transform  = 'rotate('+(-deg*rad_to_deg)+'deg)';
				props.opacity    = op;

				point.css(props);

			}).bind('mouseleave.pointPoint',function(){
				point.hide();
				pointHidden = true;
			});

		});

		this.destroyPointPoint = function(){

		    // Unbind all the event handlers
		    // and remove() the pointers 

			$('html').unbind('.pointPoint');

			$.each(pointers,function(){
				this.remove();
			});

		};

		return this;
	};

})(jQuery);</pre>
<p>When you call <strong>pointPoint()</strong>, it creates an event listener for the mousemove event. Inside it, the plugin calculates the position and rotation of the arrow using trigonometry functions. Check out <a href="http://en.wikipedia.org/wiki/Right_triangle" target="_blank">this Wikipedia article</a> if you&#8217;d like to learn more.</p>
<p>I am also using the <a href="https://github.com/brandonaaron/jquery-cssHooks/" target="_blank">transform.js CSS hooks for jQuery</a>, which level the support for CSS3 rotations in browsers that support them (this means the plugin <strong>will not work in IE678</strong>).</p>
<div id="attachment_1613" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/09/jquery-pointpoint-plugin/"><img class="size-full wp-image-1613" title="jQuery PointPoint Plugin" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/09/jqueyr-pointpoint-plugin.jpg" alt="jQuery PointPoint Plugin" width="620" height="260" /></a><p class="wp-caption-text">jQuery PointPoint Plugin</p></div>
<h3>How to use it</h3>
<p>To include <em>jQuery PointPoint</em> in your website, you need to copy the <strong>jquery.pointpoint</strong> folder (located in <em>/assets</em> in the downloadable zip) in your directory structure. After this, all you need to do is include the two js files and the stylesheet, that you find inside, in your page. Refer to <em>index.html</em> as an example.</p>
<p>The plugin itself is simple to use. You just need to call it on the element which you need to point to. The plugin will automatically find the position of the element and update the arrow when you move the mouse. You can also pass an arguments object with two properties &#8211; &#8220;<em><strong>class</strong></em>&#8221; and &#8220;<em><strong>distance</strong></em>&#8220;.</p>
<pre class="brush:js">$('#pushButton').pointPoint();

/*
    // You can also pass arguments:
    $('#pushButton').pointPoint({
        "class":"myNewPointer",
        "distance":100
    });
*/</pre>
<p>The snippet above adds an arrow next to the mouse cursor, which points to the element with an id of &#8220;<strong>pushButton</strong>&#8220;. The arguments in the second example will set a custom class on the arrow (in case you want to customize the styling) and move it further away from the mouse cursor. The default styles of the arrow are defined in <em><strong>jquery.pointpoint.css</strong></em>.</p>
<p>When you call the plugin, it returns a jQuery object, so you can use it inside method call chains. There is one one minor difference, however &#8211; this object has an additional method &#8211; <strong>destroyPointPoint()</strong>, which you can use to cancel the plugin:</p>
<pre class="brush:js">var pp = $('#pushButton').pointPoint();

$('body').click(function(){
    pp.destroyPointPoint();
});</pre>
<p>This will remove all arrows and destroy the event listeners for the mouse move event.</p>
<h3>We are done!</h3>
<p>I hope you find the plugin useful and only use it for good, not evil. As usual, share your suggestions in the comments section.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/09/jquery-pointpoint-plugin/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>Shuffle Letters Effect: a jQuery Plugin</title>
		<link>http://tutorialzine.com/2011/09/shuffle-letters-effect-jquery/</link>
		<comments>http://tutorialzine.com/2011/09/shuffle-letters-effect-jquery/#comments</comments>
		<pubDate>Fri, 02 Sep 2011 13:43:31 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1597</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2011/09/shuffle-letters-effect-jquery/"><img src="http://cdn.tutorialzine.com/img/featured/1597.jpg" /></a></div> In this short tutorial we will be making a jQuery plugin that will shuffle the text content of any DOM element - an interesting effect that can be used in headings, logos and slideshows.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2011/09/shuffle-letters-effect-jquery/"><img src="http://cdn.tutorialzine.com/img/featured/1597.jpg" /></a></div> <p>In this short tutorial we will be making a jQuery plugin that will shuffle the text content of any DOM element &#8211; an interesting effect that can be used in headings, logos and slideshows.</p>
<blockquote class="note"><p><strong>Updated on 10 Sep 2011</strong>: The plugin was slightly improved by including a callback function, called when the animation is complete. Just pass it as a property of the arguments object: $(&#8216;#el&#8217;).shuffleLetters({callback:function(){}});</p></blockquote>
<h3>The Code</h3>
<p>The first step is to write the backbone of our jQuery plugin. We will place the code inside a self-executing anonymous function, and extend <strong>$.fn</strong>.</p>
<h4>assets/js/jquery.shuffleLetters.js</h4>
<pre class="brush:js">(function($){

	$.fn.shuffleLetters = function(prop){

		// Handling default arguments
		var options = $.extend({
			// Default arguments
		},prop)

		return this.each(function(){
			// The main plugin code goes here
		});
	};

	// A helper function

	function randomChar(type){
		// Generate and return a random character
	}

})(jQuery);</pre>
<p>Next we will turn our attention to the <code>randomChar()</code> helper function. It will take a type argument (one of &#8220;<strong>lowerLetter</strong>&#8220;, &#8220;<strong>upperLetter</strong>&#8221; or &#8220;<strong>symbol</strong>&#8220;) and return a random character.</p>
<pre class="brush:js">function randomChar(type){
	var pool = "";

	if (type == "lowerLetter"){
		pool = "abcdefghijklmnopqrstuvwxyz0123456789";
	}
	else if (type == "upperLetter"){
		pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	}
	else if (type == "symbol"){
		pool = ",.?/\\(^)![]{}*&amp;^%$#'\"";
	}

	var arr = pool.split('');
	return arr[Math.floor(Math.random()*arr.length)];
}</pre>
<p>We could have used a single pool string for all types of characters, but this will do for a better effect.</p>
<div id="attachment_1599" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/09/shuffle-letters-effect-jquery/"><img class="size-full wp-image-1599" title="The Plugin In Action" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/09/jquery-shuffle-letters.jpg" alt="The Plugin In Action" width="620" height="260" /></a><p class="wp-caption-text">The Plugin In Action</p></div>
<p>Now lets write the body of the plugin!</p>
<pre class="brush:js">$.fn.shuffleLetters = function(prop){

	var options = $.extend({
		"step"	: 8,	// How many times should the letters be changed
		"fps"	: 25,	// Frames Per Second
		"text"	: "" 	// Use this text instead of the contents
	},prop)

	return this.each(function(){

		var el = $(this),
			str = "";

		if(options.text) {
			str = options.text.split('');
		}
		else {
			str = el.text().split('');
		}

		// The types array holds the type for each character;
		// Letters holds the positions of non-space characters;

		var types = [],
			letters = [];

		// Looping through all the chars of the string

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

			var ch = str[i];

			if(ch == " "){
				types[i] = "space";
				continue;
			}
			else if(/[a-z]/.test(ch)){
				types[i] = "lowerLetter";
			}
			else if(/[A-Z]/.test(ch)){
				types[i] = "upperLetter";
			}
			else {
				types[i] = "symbol";
			}

			letters.push(i);
		}

		el.html("");			

		// Self executing named function expression:

		(function shuffle(start){

			// This code is run options.fps times per second
			// and updates the contents of the page element

			var i,
				len = letters.length,
				strCopy = str.slice(0);	// Fresh copy of the string

			if(start&gt;len){
				return;
			}

			// All the work gets done here
			for(i=Math.max(start,0); i &lt; len; i++){

				// The start argument and options.step limit
				// the characters we will be working on at once

				if( i &lt; start+options.step){
					// Generate a random character at this position
					strCopy[letters[i]] = randomChar(types[letters[i]]);
				}
				else {
					strCopy[letters[i]] = "";
				}
			}

			el.text(strCopy.join(""));

			setTimeout(function(){

				shuffle(start+1);

			},1000/options.fps);

		})(-options.step);

	});
};</pre>
<p>The plugin will take either the <strong>contents</strong> of the DOM element it was called on, or the <strong>text</strong> property of the object passed as an argument. It then splits the string into characters and determines the type of each one. The shuffle function then uses <code>setTimeout()</code> to call itself and randomize the string, updating the DOM element on each step.</p>
<p>When you head on to the demo you will see that you are able to type your own text and test it out. Here is how I did it:</p>
<h4>assets/js/script.js</h4>
<pre class="brush:js">$(function(){

	// container is the DOM element;
	// userText is the textbox

	var container = $("#container")
		userText = $('#userText'); 

	// Shuffle the contents of container
	container.shuffleLetters();

	// Bind events
	userText.click(function () {

	  userText.val("");

	}).bind('keypress',function(e){

		if(e.keyCode == 13){

			// The return key was pressed

			container.shuffleLetters({
				"text": userText.val()
			});

			userText.val("");
		}

	}).hide();

	// Leave a 4 second pause

	setTimeout(function(){

		// Shuffle the container with custom text
		container.shuffleLetters({
			"text": "Test it for yourself!"
		});

		userText.val("type anything and hit return..").fadeIn();

	},4000);

});</pre>
<p>The fragment above also shows how you can use the plugin and the custom <strong>text</strong> parameter.</p>
<h3>Done</h3>
<p>I hope you find this plugin useful and have fun with it. It is released under the MIT license.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/09/shuffle-letters-effect-jquery/feed/</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
		<item>
		<title>Building a Website with PHP, MySQL and jQuery Mobile, Part 2</title>
		<link>http://tutorialzine.com/2011/08/jquery-mobile-mvc-website-part-2/</link>
		<comments>http://tutorialzine.com/2011/08/jquery-mobile-mvc-website-part-2/#comments</comments>
		<pubDate>Tue, 23 Aug 2011 12:34:01 +0000</pubDate>
		<dc:creator>Martin Angelov</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://tutorialzine.com/?p=1585</guid>
		<description><![CDATA[<div><a href="http://tutorialzine.com/2011/08/jquery-mobile-mvc-website-part-2/"><img src="http://cdn.tutorialzine.com/img/featured/1585.jpg" /></a></div> In the second part of this two-part tutorial, we will complete our MVC driven computer web store by writing the views and discussing jQuery mobile.]]></description>
			<content:encoded><![CDATA[<div><a href="http://tutorialzine.com/2011/08/jquery-mobile-mvc-website-part-2/"><img src="http://cdn.tutorialzine.com/img/featured/1585.jpg" /></a></div> <p>This is the second part of a two-part tutorial, in which we use PHP, MySQL and jQuery mobile to build a simple computer web store. <a title="Go to Part 1" href="http://tutorialzine.com/2011/08/jquery-mobile-product-website/">In the previous part</a> we created the models and the controllers, and this time we will be writing our views.</p>
<h3>jQuery mobile</h3>
<p>First, lets say a few words about the library we will be using. <a href="http://jquerymobile.com/" target="_blank">jQuery mobile</a> is a user interface library that sits on top of jQuery and provides support for a wide array of devices in the form of ready to use widgets and a touch-friendly development environment. It is still in beta, but upgrading to the official 1.0 release will be as simple as swapping a CDN URL.</p>
<p>The library is built around progressive enhancement. You, as the developer, only need to concern yourself with outputting the correct HTML, and the library will take care of the rest. jQuery mobile makes use of the HTML5 <strong>data-</strong> attributes and by adding them, you instruct the library how it should render your markup.</p>
<p>In this tutorial we will be using some of the interface components that this library gives us &#8211; <a href="http://jquerymobile.com/demos/1.0b2/#/demos/1.0b2/docs/lists/docs-lists.html" target="_blank">lists</a>, <a href="http://jquerymobile.com/demos/1.0b2/#/demos/1.0b2/docs/toolbars/docs-headers.html" target="_blank">header</a> and <a href="http://jquerymobile.com/demos/1.0b2/#/demos/1.0b2/docs/toolbars/docs-footers.html" target="_blank">footer</a> bars and <a href="http://jquerymobile.com/demos/1.0b2/#/demos/1.0b2/docs/buttons/buttons-types.html" target="_blank">buttons</a>, all of which are defined using the <strong>data-role</strong> attributes, which you will see in use in the next section.</p>
<h3>Rendering Views</h3>
<p>The views are PHP files, or templates, that generate HTML code. They are printed by the controllers using the <strong>render()</strong> helper function. We have 7 views in use for this website &#8211; <em>_category.php</em>, <em>_product.php</em>, <em>_header.php</em>, <em>_footer.php</em>, <em>category.php</em>, <em>home.php</em> and <em>error.php</em>, which are discussed later on. First, here is <strong>render() </strong>function:</p>
<h4>includes/helpers.php</h4>
<pre class="brush:php">/* These are helper functions */

function render($template,$vars = array()){

	// This function takes the name of a template and
	// a list of variables, and renders it.

	// This will create variables from the array:
	extract($vars);

	// It can also take an array of objects
	// instead of a template name.
	if(is_array($template)){

		// If an array was passed, it will loop
		// through it, and include a partial view
		foreach($template as $k){

			// This will create a local variable
			// with the name of the object's class

			$cl = strtolower(get_class($k));
			$$cl = $k;

			include "views/_$cl.php";
		}

	}
	else {
		include "views/$template.php";
	}
}</pre>
<p>The first argument of this function is the name of the template file in the <strong>views/</strong> folder (without the <em>.php</em> extension). The next is an array with arguments. These are extracted and form real variables which you can use in your template.</p>
<p>There is one more way this function can be called &#8211; instead of a template name, you can pass an array with objects. If you recall from last time, this is what is returned by using the <strong>find()</strong> method. So basically if you pass the result of <code>Category::find()</code> to <strong>render</strong>, the function will loop through the array, get the class names of the objects inside it, and automatically include the <strong>_category.php</strong> template for each one. Some frameworks (Rails for example) call these partials.</p>
<div id="attachment_1579" class="wp-caption alignnone" style="width: 630px"><a href="http://demo.tutorialzine.com/2011/08/jquery-mobile-product-website/"><img class="size-full wp-image-1579" title="Computer Store with PHP, MySQL and jQuery Mobile" src="http://cdn.tutorialzine.com/wp-content/uploads/2011/08/mobile-computer-store.jpg" alt="Computer Store with PHP, MySQL and jQuery Mobile" width="620" height="460" /></a><p class="wp-caption-text">Computer Store with PHP, MySQL and jQuery Mobile</p></div>
<h3>The Views</h3>
<p>Lets start off with the first view &#8211; the header. You can see that this template is simply the top part of a regular HTML5 page with interleaved PHP code. This view is used in <strong>home.php</strong> and <strong>category.php</strong> to promote code reuse.</p>
<h4>includes/views/_header.php</h4>
<pre class="brush:html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
	&lt;head&gt;
	&lt;title&gt;&lt;?php echo formatTitle($title)?&gt;&lt;/title&gt; 

	&lt;meta name="viewport" content="width=device-width, initial-scale=1" /&gt; 

	&lt;link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css" /&gt;
    &lt;link rel="stylesheet" href="assets/css/styles.css" /&gt;
	&lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"&gt;&lt;/script&gt;
	&lt;script type="text/javascript" src="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt; 

&lt;div data-role="page"&gt;

	&lt;div data-role="header" data-theme="b"&gt;
	    &lt;a href="./" data-icon="home" data-iconpos="notext" data-transition="fade"&gt;Home&lt;/a&gt;
		&lt;h1&gt;&lt;?php echo $title?&gt;&lt;/h1&gt;
	&lt;/div&gt;

	&lt;div data-role="content"&gt;</pre>
<p>In the head section we include jQuery and jQuery mobile from jQuery&#8217;s CDN, and two stylesheets. The body section is where it gets interesting. We define a div with the <strong>data-role=&#8221;page&#8221;</strong> attribute. This, along with the <strong>data-role=&#8221;content&#8221;</strong> div, are the two elements <a href="http://jquerymobile.com/demos/1.0b2/#/demos/1.0b2/docs/pages/page-anatomy.html" target="_blank">required by the library to be present on every page</a>.</p>
<p>The <strong>data-role=&#8221;header&#8221;</strong> div is transformed into a header bar. The <strong>data-theme</strong> attribute chooses one of the <a href="http://jquerymobile.com/demos/1.0b2/#/demos/1.0b2/docs/api/themes.html" target="_blank">5 standard themes</a>. Inside it, we have a link that is assigned a home icon, and has its text hidden. jQuery Mobile comes with a <a href="http://jquerymobile.com/demos/1.0b2/#/demos/1.0b2/docs/buttons/buttons-icons.html" target="_blank">set of icons</a> you can choose from.</p>
<p>The closing tags (and the footer bar) reside in the <em>_footer.php</em> view:</p>
<h4>includes/views/_footer.php</h4>
<pre class="brush:php">	&lt;/div&gt;

	&lt;div data-role="footer" id="pageFooter"&gt;
		&lt;h4&gt;&lt;?php echo $GLOBALS['defaultFooter']?&gt;&lt;/h4&gt;
	&lt;/div&gt;
&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;</pre>
<p>Nothing too fancy here. We only have a div with the <strong>data-role=&#8221;footer&#8221;</strong> attribute, and inside it we print the globally accessible <strong>$defaultFooter</strong> variable, defined in <strong>includes/config.php</strong>.</p>
<p>Neither of the above views are printed directly by our controllers. They are instead used by <strong>category.php</strong> and <strong>home.php</strong>:</p>
<h4>includes/views/home.php</h4>
<pre class="brush:php">&lt;?php render('_header',array('title'=&gt;$title))?&gt;

&lt;p&gt;Welcome! This is a demo for a ...&lt;/p&gt;
&lt;p&gt;Remember to try browsing this ...&lt;/p&gt;

&lt;ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b"&gt;
    &lt;li data-role="list-divider"&gt;Choose a product category&lt;/li&gt;
    &lt;?php render($content) ?&gt;
&lt;/ul&gt;

&lt;?php render('_footer')?&gt;</pre>
<p>If you may recall, the home view was rendered in the home controller. There we passed an array with all the categories, which is available here as <code>$content</code>. So what this view does, is to print the header, and footer, define a jQuery mobile listview (using the data-role attribute), and generate the markup of the categories passed by the controller, using this template (used implicitly by <strong>render()</strong>):</p>
<h4>index.php/views/_category.php</h4>
<pre class="brush:php">&lt;li &lt;?php echo ($active == $category-&gt;id ? 'data-theme="a"' : '') ?&gt;&gt;
&lt;a href="?category=&lt;?php echo $category-&gt;id?&gt;" data-transition="fade"&gt;
	&lt;?php echo $category-&gt;name ?&gt;
    &lt;span class="ui-li-count"&gt;&lt;?php echo $category-&gt;contains?&gt;&lt;/span&gt;&lt;/a&gt;
&lt;/li&gt;</pre>
<p>Notice that we have a <code>$category</code> PHP variable that points to the actual object this view is being generated for. This is done in lines 24/25 of the render function. When the user clicks one of the links generated by the above fragment, he will be taken to the <strong>/?category=someid</strong> url, which will show the <strong>category.php</strong> view, given below.</p>
<pre class="brush:php">&lt;?php render('_header',array('title'=&gt;$title))?&gt;

&lt;div class="rightColumn"&gt;
	&lt;ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="c"&gt;
        &lt;?php render($products) ?&gt;
    &lt;/ul&gt;
&lt;/div&gt;

&lt;div class="leftColumn"&gt;
    &lt;ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b"&gt;
        &lt;li data-role="list-divider"&gt;Categories&lt;/li&gt;
        &lt;?php render($categories,array('active'=&gt;$_GET['category'])) ?&gt;
    &lt;/ul&gt;
&lt;/div&gt;

&lt;?php render('_footer')?&gt;</pre>
<p>This file also uses the header, footer and _category views, but it also presents a column with products (passed by the category controller). The products are rendered using the <em>_product.php</em> partial:</p>
<pre class="brush:php">&lt;li class="product"&gt;
	&lt;img src="assets/img/&lt;?php echo $product-&gt;id ?&gt;.jpg" alt="&lt;?php echo $product-&gt;name ?&gt;" /&gt;
	&lt;?php echo $product-&gt;name ?&gt; &lt;i&gt;&lt;?php echo $product-&gt;manufacturer?&gt;&lt;/i&gt;
	&lt;b&gt;$&lt;?php echo $product-&gt;price?&gt;&lt;/b&gt;
&lt;/li&gt;</pre>
<p>As we have an image as the first child of the li elements, it is automatically displayed as an 80px thumbnail by jQuery mobile.</p>
<p>One of the advantages to using the interface components defined in the library is that they are automatically scaled to the width of the device. But what about the columns we defined above? We will need to style them ourselves with some CSS3 magic:</p>
<h4>assets/css/styles.css</h4>
<pre class="brush:css">media all and (min-width: 650px){

	.rightColumn{
		width:56%;
		float:right;
		margin-left:4%;
	}

	.leftColumn{
		width:40%;
		float:left;
	}

}

.product i{
	display:block;
	font-size:0.8em;
	font-weight:normal;
	font-style:normal;
}

.product img{
	margin:10px;
}

.product b{
	position: absolute;
	right: 15px;
	top: 15px;
	font-size: 0.9em;
}

.product{
	height: 80px;
}</pre>
<p>Using a media query, we tell the browser that if the view area is wider than 650px, it should display the columns side by side. If it is not (or if the browser does not support media queries) they will be displayed one on top of the other, the regular &#8220;block&#8221; behavior.</p>
<h3>We&#8217;re done!</h3>
<p>In the second and last part of this tutorial, we wrote our views to leverage the wonderful features of jQuery mobile. With minimal effort on our part, we were able to describe the roles of our markup and easily create a fully fledged mobile website.</p>
]]></content:encoded>
			<wfw:commentRss>http://tutorialzine.com/2011/08/jquery-mobile-mvc-website-part-2/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using apc
Page Caching using apc
Object Caching 701/757 objects using apc
Content Delivery Network via cdn.tutorialzine.com

Served from: tutorialzine.com @ 2012-02-08 13:12:04 -->
