<?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>Samson Muhangi</title>
	<atom:link href="http://webdevhub.co.uk/feed/" rel="self" type="application/rss+xml" />
	<link>http://webdevhub.co.uk</link>
	<description>JavaScript, HTML5, CSS3,  and RWD goodness!</description>
	<lastBuildDate>Tue, 25 Mar 2014 11:21:06 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.3.34</generator>
	<item>
		<title>HTML5 classList API</title>
		<link>http://webdevhub.co.uk/html5-classlist-api/</link>
		<comments>http://webdevhub.co.uk/html5-classlist-api/#comments</comments>
		<pubDate>Wed, 03 Jul 2013 20:48:27 +0000</pubDate>
		<dc:creator><![CDATA[Samson Muhangi]]></dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://webdevhub.co.uk/?p=1045</guid>
		<description><![CDATA[DOM element class attributes are not only used as &#8216;hooks&#8217; in CSS to create selectors by which developers and designers style pages, they are widely used in JavaScript for DOM programming. They are an integral part of front-end web development, and used by developers on a daily basis. Hitherto, working with classes natively has been &#8230; <a href="http://webdevhub.co.uk/html5-classlist-api/">Read more <span class="meta-nav">&#62;&#62;</span></a>]]></description>
				<content:encoded><![CDATA[<div><span><img class="img-media" src="/wp-content/themes/twentyeleven/images/html5js_ft.png" alt="html5 classList" title="HTML5 classList" /></span></div>
<p>DOM element class attributes are not only used as &#8216;hooks&#8217; in <abbr title="Cascading Style Sheets">CSS</abbr> to create selectors by which developers and designers style pages, they are widely used in JavaScript for <abbr title="Document Object Model">DOM</abbr> programming. They are an integral part of front-end web development, and used by developers on a daily basis.</p>
<p>Hitherto, working with classes natively has been arduous. This has contributed to the rise in popularity of libraries that provide helper methods. jQuery for example, provides <code>addClass()</code>, <code>hasClass()</code>, <code>removeClass()</code>, and <code>toggleClass()</code>. These methods make working with classes a breeze. Surely, these methods should be available natively. Well, guess what? In addition to an array of new JavaScript APIs, HTML5 replenishes native JavaScript with <code>classList</code>.</p>
<p>The <code>classList</code> object provides the <em>add</em>, <em>remove</em>, <em>contains</em> and <em>toggle</em> methods to facilitate easy and quick class manipulation natively by developers. Let&#8217;s explore.</p>
<h2>elem.classList</h2>
<p>The classList object has the following properties:<br />
<span class="code-normal4">{<br />
    &nbsp;&nbsp;&nbsp;length: number, <span class="snip-comment">// returns a class count</span><br />
    &nbsp;&nbsp;&nbsp;item: function(){ },  <span class="snip-comment">// index</span><br />
    &nbsp;&nbsp;&nbsp;contains: function() { },<br />
    &nbsp;&nbsp;&nbsp;add: function(){ },<br />
    &nbsp;&nbsp;&nbsp;remove: function(){ }<br />
}</span></p>
<h2>elem.classList.contains(class)</h2>
<p>The <code>contains()</code> method is used to check whether a class exists on the node or not. It returns a boolean value; <em>true</em> or <em>false</em>. </p>
<p>usage:<br />
<span class="code-normal4">var myElem = document.querySelector(&#8216;#wrapper&#8217;);<br />
myElem.classList.contains(&#8216;parent&#8217;);<span class="snip-comment">// returns true or false</span></span></p>
<h2>elem.classList.add(class)</h2>
<p>The <code>add()</code> method, as you might have gathered, adds a class to the selected node.</p>
<p>usage:<br />
<span class="code-normal4">myElem.classList.add(&#8216;new-class&#8217;);</span></p>
<h2>elem.classList.remove(class)</h2>
<p>Conversely, the <code>remove()</code> method removes the &#8216;passed&#8217; class from the selected element.</p>
<p>usage:<br />
<span class="code-normal4">myElem.classList.remove(&#8216;new-class&#8217;);</span></p>
<h2>elem.classList.toggle(class)</h2>
<p>Yes, you guessed it, the <code>toggle()</code> method adds and removes the class. So, if the class exists, it is removed, and vice versa.</p>
<p>usage:<br />
<span class="code-normal4">myElem.classList.toggle(&#8216;my-class&#8217;);</span></p>
<p>This is predominately used with events such as <em>click</em> and <em>hover</em>.</p>
<h2>Browser support</h2>
<p><code>classList</code> is well supported in modern browsers and as of this writing, according to canisue.com, global browser support stands at 75.6%. If you are supporting legacy IE, be sure to use a fall back for IE9 and below.</p>
<h2>Useful resources</h2>
<ul>
<li><a href="https://github.com/eligrey/classList.js" class="ext-link">Cross browser classList</a></li>
<li><a href="http://caniuse.com/#search=classList" class="ext-link">caniuse.com</a></li>
<li><a href="http://www.w3.org/TR/dom/#dom-element-classlist" class="ext-link">w3c classList specification</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://webdevhub.co.uk/html5-classlist-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HTML5 &#8211; Link and DNS prefetching</title>
		<link>http://webdevhub.co.uk/html5-link-and-dns-prefetching/</link>
		<comments>http://webdevhub.co.uk/html5-link-and-dns-prefetching/#comments</comments>
		<pubDate>Tue, 04 Jun 2013 08:03:44 +0000</pubDate>
		<dc:creator><![CDATA[Samson Muhangi]]></dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Mobile]]></category>

		<guid isPermaLink="false">http://webdevhub.co.uk/?p=995</guid>
		<description><![CDATA[In a world where instant gratification is paramount, it is imperative that our web applications are optimized for speed and performance. HTML5 has two features that many developers are unaware of, namely prefetch and prerender. &#8216;Excuse-moi?&#8217; I hear you say. Well maybe not in French, but you know what I mean. Let me elaborate. Link &#8230; <a href="http://webdevhub.co.uk/html5-link-and-dns-prefetching/">Read more <span class="meta-nav">&#62;&#62;</span></a>]]></description>
				<content:encoded><![CDATA[<div><span><img class="img-media" src="/wp-content/themes/twentyeleven/images/prefetching.jpg" alt="link and dns prefetching" title="link and dns prefetcing" /></span></div>
<p>In a world where instant gratification is paramount, it is imperative that our web applications are optimized for speed and performance. HTML5 has two features that many developers are unaware of, namely prefetch and prerender. &#8216;Excuse-moi?&#8217; I hear you say. Well maybe not in French, but you know what I mean. Let me elaborate.</p>
<h2>Link prefetching and prerendering</h2>
<p>The <span class="code2">prefetch</span> HTML5 feature allows the developer to silently fetch a page or asset as soon as the page loads. This page or asset will therefore instantly load when the user makes the request via a designated link. This feature only fetches that exact specified resource (URL).</p>
<blockquote><p>Content prefetching and prerendering can be invaluable in dramatically speeding up your website by shaving off valuable milliseconds on http latency.</p></blockquote>
<p>This dramatically improves load speeds of your pages and is especially useful for mobile applications. </p>
<p><span class="code2">Prerender</span> on the other hand will render the whole page in the background albeit with some limitations. Use these features sparingly however, as over use can prove counter productive (Well, like anything in life, too much of anything is&#8230;). Only <span class="code2">prerender</span> pages that are likely to be visited by the user. And the code? In the <span class="code2">head</span> section of your web page, add the following code replacing the <span class="code2">href</span> values with your own.</p>
<h2>Prefetch and Prerender examples</h2>
<pre class="snippet">

&lt;link rel=<span class="snip-val">"prerender"</span> href=<span class="snip-val">"http://www.webdevhub.co.uk/about-me.html"</span> /&gt;
&lt;link rel=<span class="snip-val">"prefetch"</span> href=<span class="snip-val">"http://www.webdevhub.co.uk/assets/my_logo.png"</span> /&gt;
</pre>
<p>Adding the code above to the <span class="code2">head</span> section will <span class="code2">prerender</span> the <em>about-me.html</em> and <span class="code2">prefetch</span> <em>my_logo.png</em> in the background as soon as the page loads making those two items available as soon as they are requested. Since a round trip to the server is not required when the user clicks on the about me link, the page will load almost instantaneously. </p>
<h2>DNS Fetching</h2>
<p>In order to reach a given hostname, the browser needs to do some work to resolve the underlying domain or <abbr title="Domain Name System">DNS</abbr>. This has a speed overhead. DNS prefetching allows you to manually specify which domains to prefetch and here is the magic:</p>
<h2>DNS prefetching</h2>
<pre class="snippet">

&lt;link rel=<span class="snip-val">"dns-prefetch"</span> href=<span class="snip-val">"http://www.asp.net/ajaxlibrary/cdn.ashx"</span> /&gt;
&lt;link rel=<span class="snip-val">"dns-prefetch"</span> href=<span class="snip-val">"//ajax.googleapis.com/ajax/libs"</span> /&gt;
</pre>
<p>In the code above we are explicitly telling the browser to resolve the two domains. This is all done in the background unobtrusively and in turn improving HTTP latency.  </p>
<p>Google uses prefetching on its results page to provide instant pages. As soon as you enter your search query and  Google is fairly certain of what you are looking for, it starts prerendering the pages using the techniques above. So when you click on any of the results, the page appears to load almost instantaneously. </p>
<p>Support and implementation of the above features is still in flux but, here is a simple guide to follow;</p>
<h3>Chrome</h3>
<p>prerender &#8211; resolves DNS, loads URL, loads whole page.<br />
DNS-prefetch &#8211; resolves DNS.</p>
<h3>Firefox</h3>
<p>prefetch &#8211; resolves DNS, loads URL<br />
DNS-prefetch &#8211; resolves DNS.</p>
<h3>IE9+</h3>
<p>DNS-prefetch &#8211; resolves DNS.</p>
<p>If you want to <span class="code2">prerender</span> a page in browsers that support this feature (Chrome), and <span class="code2">prefetch</span> in other browsers (Firefox and IE9+), you can pass both features in the <span class="code2">rel</span> attribute.<br />
<span class="code-normal2">&nbsp;&nbsp;&lt;link rel=&#8221;prefetch prerender&#8221; href=&#8221;&#8230;&#8221; /&gt;</span></p>
<p>In conclusion, patchy support should not stop you from using these and other HTML5 features in your projects, as long as you provide a fall back where possible for browsers that do not support a given feature. </p>
<p>Happy coding!  </p>
]]></content:encoded>
			<wfw:commentRss>http://webdevhub.co.uk/html5-link-and-dns-prefetching/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The HTML5 datalist element</title>
		<link>http://webdevhub.co.uk/the-html5-datalist-element/</link>
		<comments>http://webdevhub.co.uk/the-html5-datalist-element/#comments</comments>
		<pubDate>Thu, 02 May 2013 13:06:53 +0000</pubDate>
		<dc:creator><![CDATA[Samson Muhangi]]></dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Mobile]]></category>

		<guid isPermaLink="false">http://webdevhub.co.uk/?p=908</guid>
		<description><![CDATA[I speak for many a developer when are I say that until recently, web forms were one of the most mundane and uninspiring elements of a web page. As a matter of fact, I had disdain for creating and using web forms. But thanks to an array of HTML5 form attributes, input types and elements &#8230; <a href="http://webdevhub.co.uk/the-html5-datalist-element/">Read more <span class="meta-nav">&#62;&#62;</span></a>]]></description>
				<content:encoded><![CDATA[<div><span><img class="img-media" src="/wp-content/themes/twentyeleven/images/html5_datalist.png" alt="html5 datalist" title="html5 datalist" /></span></div>
<p>I speak for many a developer when are I say that until recently, web forms were one of the most mundane and uninspiring elements of a web page. As a matter of fact, I had disdain for creating and using web forms. But thanks to an array of HTML5 form attributes, input types and elements this is no longer the case. In this post I am going to focus on the <span class="code2">datalist</span> element. </p>
<p>The <span class="code2">datalist</span> element enables you as a developer to provide a predefined list of values to the user as well as allowing them to enter their own. The <span class="code2">datalist</span> element is used with an <span class="code2">input</span> element using the <span class="code2">list</span> attribute, to link it to the <span class="code2">datalist</span>. For example;<br />
<span class="code-normal2">&lt;input value=&#8221;&#8221; list=&#8221;fruits&#8221; /&gt;<br />
&lt;datalist id=&#8221;fruits&#8221;&gt;&lt;/datalist&gt;<br />
</span></p>
<p>The <span class="code2">list</span> attribute above links the <span class="code2">input</span> field to the <span class="code2">datalist</span> via the <span class="code2">datalist</span> id, in this case <span class="code2">id=&#8221;fruits&#8221;</span>.</p>
<p>You can then nest <span class="code2">options</span> inside the <span class="code2">datalist</span> element. Let&#8217;s have a look at a handful of examples.</p>
<h2>input[type=text]</h2>
<p>For text input fields, the <span class="">datalist</span> element allows us to set a predefined list analogous to a drop down list. The user is however not limited to the predefined list items. Unlike the drop down list, the user can still enter items not on the list, as I illustrate in the demo below.</p>
<div>
<input type="text" placeholder="Enter your favorite editor" class="text" list="editors" /><br />
<datalist id="editors"><option value="Notepad++"/><option value="Sublime Text"/><option value="Dreamweaver"/><option value="Textmate"/><option value="Coda"/><option value="e-texteditor"/><option value="Vim"/><option value="UltraEdit"/><br />
</datalist>
</div>
<p>here is the code;</p>
<pre class="highlight-me">
&lt;input type="text"  list="editors" /&gt;
&lt;datalist id="editors"&gt;
&nbsp;&nbsp;&lt;option value="Notepad++" /&gt;
&nbsp;&nbsp;&lt;option value="Sublime Text" /&gt;
&nbsp;&nbsp;&lt;option value="Dreamweaver" /&gt;
&nbsp;&nbsp;&lt;option value="Coda" /&gt;
&nbsp;&nbsp;&lt;option value="e-texteditor" /&gt;
&nbsp;&nbsp;&lt;option value="Vim" /&gt;
&nbsp;&nbsp;&lt;option value="UltraEdit" /&gt;
&lt;/datalist&gt;
</pre>
<h2>input[type=date]</h2>
<p>Most modern browsers handle the date <span class="code2">input</span> field well. <span class="code2">datalist</span> takes it that one step further by allowing you to add suggested dates and specify labels.</p>
<div>
<input type="date" list="dates" id="date" /><br />
<span class="warning" style="display:none">input[type=date] is not available in this browser</span><br />
<datalist id="dates"><option label="Christmas day">2013-12-25</option><option label="Labour day">2013-05-01</option><option label="Birthday">2013-11-26</option></datalist>
</div>
<pre class="highlight-me">
&lt;input type="date"  list="dates" /&gt;
&lt;datalist id="dates"&gt;
&nbsp;&nbsp;&lt;option value="Christmas day"&gt;2013-12-25&lt;/option&gt;
&nbsp;&nbsp;&lt;option value="Labour day"&gt;2013-05-01&lt;/option&gt;
&nbsp;&nbsp;&lt;option value="Birthday"&gt;2013-11-26&lt;/option&gt;
&lt;/datalist&gt;
</pre>
<h2>input[type=range]</h2>
<p>If you are not familiar with range <span class="code2">input</span> type, it allows the user to pick a value from a given range. You can extend this with our new found friend <span class="code2">datalist</span>, by setting predefined markers of values for the user to pick from.</p>
<div>
<input type="range" id="range" value="0" min="0" max="90" list="ranges" /><output for="range">0</output><br />
<span class="warning" style="display:none">input[type=range] is not available in this browser</span><br />
<datalist id="ranges"><option>15</option><option>30</option><option>45</option><option>60</option><option>75</option></datalist><br />
<script>
	document.querySelector('#range').onchange = function(e){
		e.target.nextElementSibling.innerText = e.target.value;
	}
</script>
</div>
<pre class="highlight-me">
&lt;input type="range" value="0" min="0" max="90" list="ranges" id="range" /&gt;
&lt;output for="range" &gt;0&lt;/output&gt;
&lt;datalist id="ranges"&gt;
&nbsp;&nbsp;&lt;option&gt;0&lt;/option&gt;
&nbsp;&nbsp;&lt;option&gt;15&lt;/option&gt;
&nbsp;&nbsp;&lt;option&gt;30&lt;/option&gt;
&nbsp;&nbsp;&lt;option&gt;45&lt;/option&gt;
&nbsp;&nbsp;&lt;option&gt;60&lt;/option&gt;
&nbsp;&nbsp;&lt;option&gt;75&lt;/option&gt;
&lt;/datalist&gt;
</pre>
<h2>input[type=color]</h2>
<p>This is another HTML5 <span class="code2">input</span> field that allows the user to select a colour from a colour picker. The <span class="code2">datalist</span> element can be used to provide a predefined list of colours. </p>
<div>
<input type="color" id="color" value="#000000" list="colours" /><br />
<span class="warning" style="display:none">input[type=color] is not available in this browser</span><br />
<datalist id="colours"><option>#c0ffee</option><option>#bada55</option><option>#0ff1ce</option><option>#b00b00</option><option>#deface</option></datalist>
</div>
<pre class="highlight-me">
&lt;input type="color" value="#000000" list="colours" /&gt;
&lt;datalist id="colours"&gt;
&nbsp;&nbsp;&lt;option &gt;#c0ffee&lt;/option&gt;
&nbsp;&nbsp;&lt;option &gt;#bada55&lt;/option&gt;
&nbsp;&nbsp;&lt;option &gt;#0ff1ce&lt;/option&gt;
&nbsp;&nbsp;&lt;option &gt;#b00b00&lt;/option&gt;
&nbsp;&nbsp;&lt;option &gt;#deface&lt;/option&gt;
&lt;/datalist&gt;
</pre>
<h2>input[type=week]</h2>
<p>Akin to the date input field, the week input type allows the user to pick weeks rather than days. With the help of <span class="code2">datalist</span>, we can again give the user a list of weeks to pick from.</p>
<div>
<input type="week" id="week" list="weeks" /><br />
<span class="warning" style="display:none">input[type=week] is not available in this browser</span><br />
<datalist id="weeks"><option label="14th Week of 2013">2013-W14</option><option label="15th Week of 2013">2013-W15</option><option label="25th Week of 2013">2013-W25</option><option label="52nd Week of 2013">2013-W52</option><option label="30th Week of 2013">2013-W30</option></datalist>
</div>
<pre class="highlight-me">
&lt;input type="week" list="weeks" /&gt;
&lt;datalist id="weeks"&gt;
&nbsp;&nbsp;&lt;option label="14th Week of 2013" &gt;2013-W14&lt;/option&gt;
&nbsp;&nbsp;&lt;option label="15th Week of 2013" &gt;2013-W15&lt;/option&gt;
&nbsp;&nbsp;&lt;option label="25th Week of 2013" &gt;2013-W25&lt;/option&gt;
&nbsp;&nbsp;&lt;option label="52nd Week of 2013" &gt;2013-W52&lt;/option&gt;
&nbsp;&nbsp;&lt;option label="30th Week of 2013" &gt;2013-W30&lt;/option&gt;
&lt;/datalist&gt;
</pre>
<h2>Conclusion</h2>
<p>I hope that gives you an insight in the <span class="code2">datalist</span> element. There are more <span class="code2">input</span> field types that can be linked to <span class="code2">datalist</span> element. I have only scratched the surface above to demonstrate its use.</p>
<p>Unfortunately, support for <span class="code2">input</span> types introduced in HTML5 is sparse, especially by Internet Explorer, where even IE10 has only implemented a handful of them. Since the <span class="code2">datalist</span> element is inextricably linked to <span class="code2">input</span> fields, you will find usage is currently limited. This however doesn&#8217;t mean you shouldn&#8217;t use these new funky elements as long as you have provisions (gracefully degrade) for unsupported browsers.</p>
<h2>Useful resources</h2>
<ul>
<li><a href="http://www.w3schools.com/tags/tag_datalist.asp">HTML datalist tag &#8211; w3c</a></li>
<li><a href="http://www.html5rocks.com/en/tutorials/forms/html5forms/">HTML5 forms &#8211; HTML5 rocks</a></li>
<li><a href="http://caniuse.com/#feat=datalist">Datalist browser compatibility</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://webdevhub.co.uk/the-html5-datalist-element/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HTML5 Geolocation API &#8211; The basics</title>
		<link>http://webdevhub.co.uk/html5-geolocation-api-the-basics/</link>
		<comments>http://webdevhub.co.uk/html5-geolocation-api-the-basics/#comments</comments>
		<pubDate>Thu, 04 Apr 2013 21:04:58 +0000</pubDate>
		<dc:creator><![CDATA[Samson Muhangi]]></dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Mobile]]></category>

		<guid isPermaLink="false">http://webdevhub.co.uk/?p=835</guid>
		<description><![CDATA[Location, location, location. No, I am not writing about real estate but rather a new HTML5 API that empowers developers by giving them the ability to get the geographical location of a user. In this post, I will cover the basics of the API &#8211; mainly how to get started &#8211; and I have also &#8230; <a href="http://webdevhub.co.uk/html5-geolocation-api-the-basics/">Read more <span class="meta-nav">&#62;&#62;</span></a>]]></description>
				<content:encoded><![CDATA[<div><span><img class="img-media" src="/wp-content/themes/twentyeleven/images/html5-geolocation-api.png" alt="html5 geolocation api" title="html5 geolocation api" /></span></div>
<p>Location, location, location. No, I am not writing about real estate but rather a new HTML5 <abbr title="Application Programming Interface">API</abbr> that empowers developers by giving them the ability to get the geographical location of a user. In this post, I will cover the basics of the API &#8211; mainly how to get started &#8211; and I have also put together a <a href="#demo">demo</a> to boot. The demo shows your approximate current location. </p>
<p>Geolocation makes the user&#8217;s location co-ordinates available to JavaScript which can then send them back to the server. This information can then be used by the developer to personalize user experience and tailor content for the end user based on location. Many retail sites, for example, tap into the geolocation API in conjunction with the Google maps API to show the user a nearby store.</p>
<p class="highlight-me">Note: The browser or device must get express permission from the user before disclosing their location.</p>
<p>All modern user agents, otherwise known as browsers, have implemented the API, albeit the implementation is still in flux. The browser or device must get express permission from the user before sending their location co-ordinates, which comes as a relief to many users who would rather not share their location with a web site or application. </p>
<h2>Get current position</h2>
<p>In its simplest form, the geolocation function is;<br />
<span class="code-normal2">function getLocation(){<br />
&nbsp; &nbsp; &nbsp; &nbsp; navigator.geolocation.getCurrentPosition(showMap)<br />
}</span><br />
Unfortunately, since the API is not implemented across all browsers at the time of this writing, we have to make provisions for antiquated browsers. This is where a really handy feature detection library called <a href="http://modernizr.com/" class="ext-link">Modernizr</a> (If you are not using it, you should) comes to the rescue. We can use Modernizr to test for geolocation support, providing a fall back where the API is not supported. Let&#8217;s rewrite the above code;<br />
<span class="code-normal2">function getLocation(){<br />
&nbsp;&nbsp;if(Modernizr.geolocation){<br />
&nbsp;&nbsp;&nbsp;&nbsp; navigator.geolocation.getCurrentPosition(showMap)<br />
&nbsp;&nbsp;}else{<br />
&nbsp;&nbsp;&nbsp;&nbsp;<span class="snip-comment">//no support, provide a fallback. Maybe</span><br />
&nbsp;&nbsp;&nbsp;} </p>
<p>}</span></p>
<h2>What happens behind the scenes</h2>
<p>Remember for the browser to send the user&#8217;s location, the user must grant permission. So when you call <span class="code2">getCurrentPosition()</span> method the following happens;</p>
<ul>
<li>The user will get a prompt alerting the user of the fact that the website wants to know their location </li>
<li>The prompt will request the user&#8217;s consent to share their location</li>
<li>The method is &#8216;blocking&#8217; so the website cannot bypass it</li>
</ul>
<p>Below is an example of a prompt you get in Chrome;</p>
<figure id="geo-loc"><img src="/wp-content/themes/twentyeleven/images/geolocation_prompt.png"/></figure>
<h2>Getting the user&#8217;s co-ordinates</h2>
<p>If the user consents to sharing their location, the callback (I have called mine showMap) will fire. The callback takes one argument which is an object that contains both the coordinates and a timestamp. Let&#8217;s write the showMap function;<br />
<span class="code-normal2">function showMap(position){<br />
&nbsp;&nbsp;var latitude = position.coords.latitude;<br />
&nbsp;&nbsp;var longitude = position.coords.longitude;<br />
<span class="snip-comment">//we can place the map on the canvas</span><br />
}</span> </p>
<p>The <span class="code2">position</span> object passed as a parameter in the <span class="code2">showMap</span> function consists of the following properties;</p>
<ul>
<li><span class="code2">coords.latitude</span> &#8211; degrees</li>
<li><span class="code2">coords.longitude</span> &#8211; degrees</li>
<li><span class="code2">coords.altitude</span> &#8211; meters</li>
<li><span class="code2">coords.accuracy</span> &#8211; meters</li>
<li><span class="code2">coords.altitudeAccuracy</span> &#8211; meters</li>
<li><span class="code2">coords.heading</span> &#8211; degrees clockwise</li>
<li><span class="code2">coords.speed</span> &#8211; meters per second</li>
<li><span class="code2">timestamp</span> &#8211; similar to the Date() object</li>
</ul>
<p>Now, working on the premise that geolocation works on a opt-in basis, we have to be prepared for some error-handling in the event that the users decides not to share their location. The second argument to our <span class="code2">getCurrentPosition()</span> method, is the error handling callback. So let&#8217;s update our function to that effect.<br />
<span class="code-normal2">navigator.geolocation.getCurrentPosition(showMap, errHandler)</span></p>
<p>If there is a problem, the <span class="code2">errHandler()</span> callback will fire. The error handler has a <span class="code2">PositionError</span> object which is one of the following;</p>
<ul>
<li><span class="code2">PERMISSION_DENIED(1)</span> &#8211; The user has denied you access to their location</li>
<li><span class="code2">POSITION_UNAVAILABLE(2)</span> &#8211; The network is down</li>
<li><span class="code2">TIMEOUT(3)</span> &#8211; It took too long to calculate the user&#8217;s position</li>
</ul>
<p>Above codes in hand, we can handle all three cases as we see fit. For example, if the user opts not to share their location, our error handler would be something like;<br />
<span class="code-normal2">function errHandler(err){<br />
&nbsp;&nbsp;if(err.code == 1){<br />
&nbsp;&nbsp;&nbsp;&nbsp;<span class="snip-comment">//user said nada</span><br />
&nbsp;&nbsp;}<br />
}</span></p>
<p>The <span class="code2">getCurrentPosition</span> function takes a third optional argument called <span class="code2">PositionOptions</span>. This is an object with three properties namely; <span class="code2">enableHighAccuracy</span>, <span class="code2">timeout</span> and <span class="code2">maximumAge</span>. As you can deduce from their names, <span class="code2">enableHighAccuracy</span> provides as an accurate a result as possible. If set to true, this might however result in a slower response. <span class="code2">Timeout</span> is the number of milliseconds your application is willing to wait for a calculation, and <span class="code2">maximumAge</span> allows the application to use a cached position within a specified time frame. I illustrate one of the three optional properties below;<br />
<span class="code-normal2">navigator.geolocation.getCurrentPosition(showMap, errHandler, {maximumAge:85000})</span></p>
<h2>Cross browser support</h2>
<p>Most modern browsers including IE9 and above support geolocation natively. However, if you are still supporting legacy IE (IE8 and below) do not despair. Help is at hand in the form of <a href="https://github.com/estebanav/javascript-mobile-desktop-geolocation/" class="ext-link">geoposition.js</a>.</p>
<h2>Geoposition.js</h2>
<p>Geoposition.js is a geolocation polyfill that not only simulates the functionality in legacy IE, it also standardizes implementation across the numerous platforms, mobile included. To use the library, simply download the script from <a href="https://github.com/estebanav/javascript-mobile-desktop-geolocation/">github</a> and call it from within your document. Remember it is a best practise to add your scripts at the bottom of the <span class="code2">body</span> section even though technically, you should add them to the <span class="code2">head</span> section. While scripts are loading, they will stop the rest of the page from loading (also referred to as blocking). By adding them to the bottom of the page, you avoid this.</p>
<h2>non-blocking geoposition script tag</h2>
<pre class="snippet">&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&nbsp;&nbsp;&lt;title&gt;&lt;/title&gt;
&lt;/head&gt;
&nbsp;&nbsp;&lt;body&gt;

&nbsp;&nbsp;&lt;script src="js/geoPosition.js"&gt;&lt;/script&gt;
&nbsp;&nbsp;&lt;/body&gt;
&lt;/html&gt;</pre>
<p>Once you have the script in place, you are now ready to use geolocation with assurances that it will work cross browser and cross platform.</p>
<h2>Implementation</h2>
<p>To initialize geolocation, do the following;<br />
<span class="code-normal2">if(geoPosition.init()){<br />
&nbsp;&nbsp;geoPosition.getCurrentPosition(successCallback, errCallback, {enableHighAccuracy:true})<br />
}else{<br />
&nbsp;&nbsp;<span class="snip-comment">//geolocation is not available on this device or browser</span><br />
}</span></p>
<p>We can now write the <span class="code2">succesCallback</span> and <span class="code2">errCallback</span> functions. </p>
<h3>Success callback</h3>
<p><span class="code-normal2">function successCallback(p){<br />
&nbsp;&nbsp;<span class="snip-comment">//p : the the geolocation object as the passed argument</span><br />
&nbsp;&nbsp;<span class="snip-comment">//p.latitude : the latitude value</span><br />
&nbsp;&nbsp;<span class="snip-comment">//p.longitude : the longitude value value</span><br />
}</span></p>
<h3>Error callback</h3>
<p><span class="code-normal2">function errCallback(p){<br />
&nbsp;&nbsp;<span class="snip-comment">//p.message : the error message</span><br />
}</span></p>
<p>The API is well documented on github, so if you are interested in all the bells and whistles, read the <a href="https://github.com/estebanav/javascript-mobile-desktop-geolocation/" class="ext-link">documentation</a>.</p>
<h2 id="demo">Demo</h2>
<p>To quickly demonstrate geolocation, if the user&#8217;s browser or device supports geolocation, I have added a simple link to this page and attached a click event listener. When the user clicks the link, the geolocation function is called and the magic happens. Otherwise, I simply display a &#8220;your browser doesn&#8217;t support geolocation&#8221; message. GIVE IT TRY!<br />
<span id="map-wrapper"></span><br />
<span id="show-map-link"></span></p>
<p class="highlight-me">Note: Remember to drop in at the <a href="https://developers.google.com/maps/documentation/javascript/tutorial" class="ext-link">google developers page</a> to grab an API key which you will need use google maps in your projects.</p>
<p>That&#8217;s it people.</p>
<h2>Useful resources</h2>
<ul>
<li><a href="https://developers.google.com/maps/documentation/javascript/tutorial">Google maps API documentation</a></li>
<li><a href="https://github.com/estebanav/javascript-mobile-desktop-geolocation/">Geoposition.js</a></li>
<li><a href="http://modernizr.com/">Modernizr</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://webdevhub.co.uk/html5-geolocation-api-the-basics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What&#8217;s new in jQuery 1.9</title>
		<link>http://webdevhub.co.uk/whats-new-in-jquery-1-9/</link>
		<comments>http://webdevhub.co.uk/whats-new-in-jquery-1-9/#comments</comments>
		<pubDate>Tue, 05 Mar 2013 22:53:15 +0000</pubDate>
		<dc:creator><![CDATA[Samson Muhangi]]></dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://webdevhub.co.uk/?p=744</guid>
		<description><![CDATA[The latest major iteration of jQuery was released on January 15, 2013. But before you run off to update your applications with jQuery 1.9, be sure to read the rest of this article. JQuery 1.9 is a major milestone in the library&#8217;s evolution as it: removes some of the deprecated features, leaving a slimmer library &#8230; <a href="http://webdevhub.co.uk/whats-new-in-jquery-1-9/">Read more <span class="meta-nav">&#62;&#62;</span></a>]]></description>
				<content:encoded><![CDATA[<div><span><img class="img-media" src="/wp-content/themes/twentyeleven/images/jquery1.png" alt="jQuery" title="What's new in jQuery 1.9" /></span></div>
<p>The latest major iteration of jQuery was released on January 15, 2013. But before you run off to update your applications with jQuery 1.9, be sure to read the rest of this article. JQuery 1.9 is a major milestone in the library&#8217;s evolution as it: </p>
<ul>
<li>removes some of the deprecated features, leaving a slimmer library (90.4kb)</li>
<li>is the last major version to support IE6,7 and 8.</li>
</ul>
<p>The removal of some of the most used but now deprecated features from the library, means that not many sites will go unaffected by simply swapping old for new as jQuery 1.9 is not backward compatible. You should not despair however as three jQuery enthusiasts have written <a href="https://github.com/jquery/jquery-migrate" class="ext-link">jQuery migrate plugin</a> which detects and re-enables deprecated features found in existing code. These are logged in the developer console making it easy for the developer to fix the issues. The plugin is very well documented and hosted on <a href="https://github.com/jquery/jquery-migrate" class="ext-link">github</a>.
<p class="highlight-me"><strong>Caveat:</strong> Make sure you load the plugin immediately after jQuery 1.9 as demonstrated below.</p>
<h2>jQuery migrate plugin</h2>
<pre class="snippet">

  &lt;script src="http://code.jquery.com/jquery-1.9.0.js" &gt;&lt;/script&gt;
  &lt;script src="http://code.jquery.com/jquery-migrate-1.1.1.js" &gt;&lt;/script&gt;
</pre>
<p class="highlight-me"><strong>Quick tip:</strong> To quickly test how your site handles the update, you can use a debugging proxy tool such as <a href="fiddler2.com" class="ext-link">fiddler</a> to swap out your current jQuery version for 1.9. This allows you to test locally without affecting any of your user&#8217;s experience.</p>
<p>The plugin will also work when upgrading to jQuery 2.0 which among other things, will be abandoning legacy IE. Is dropping support for IE6,7,8 premature? That&#8217;s a question that I am sure divides opinion but one that I am not going to address in this article.</p>
<h2>Features removed</h2>
<ul>
<li><span class="code2">die()</span> &#8211; use <span class="code2">off()</span> instead </li>
<li><span class="code2">andSelf()</span> &#8211; use <span class="code2">addBack()</span> instead</li>
<li><span class="code2">live()</span> &#8211; use <span class="code2">on()</span> instead</li>
<li>The <span class="code2">&#8220;hover&#8221;</span> pseudo event is no longer supported as a synonym for <span class="code2">&#8220;mouseenter mouseleave&#8221;</span></li>
<li><span class="code2">$.browser()</span> &#8211; removed </li>
</ul>
<p>The above list is not definitive but those are the most commonly used features that are bound to be flagged up in most code.</p>
<h2>New features</h2>
<h3><span class="code2">.css()</span> multiple property getter</h3>
<p>You can now pass an array of css properties to the <code>.css()</code> method. This will return an object of the property values passed e.g: </p>
<h2>.css() Multiple property getter</h2>
<pre class="snippet">

  var elDims = $('elm').css(['width','height','backgroundColor']);
  <span class="snip-comment">//{ width:"50px", height:"50px", backgroundColor:"#c0ffee" }</span> 
</pre>
<h3><span class="code2">.finish()</span> method</h3>
<p>Until now queued animations have been handled by the <code>.stop()</code> and <code>.clearQueue()</code> methods. <code>.finish()</code> is the new way to stop animations and place them in their final state</p>
<h3>CSS3 selector support</h3>
<p>The following CSS3 selectors are now supported in all browsers:</p>
<ul>
<li><span class="code2">:first-of-type</span></li>
<li><span class="code2">:last-of-type</span></li>
<li><span class="code2">:nth-last-child</span></li>
<li><span class="code2">:nth-last-of-type</span></li>
<li><span class="code2">:nth-of-type</span></li>
<li><span class="code2">:only-of-type</span></li>
<li><span class="code2">:target</span></li>
<li><span class="code2">:root</span></li>
</ul>
<h3><span class="code2">prop()</span> vs <span class="code2">attr()</span></h3>
<p>jQuery 1.9 encourages the use the right method for the occasion. In most cases where <code>attr()</code> is used, <code>prop()</code> is probably the right method to use albeit <code>attr()</code> working. However, the method you use should always be determined by what you are trying to retrieve or achieve. There is a very good discussion thread on <a href="http://stackoverflow.com/questions/5874652/prop-vs-attr" class="ext-link">stackoverflow</a> that explains the difference. </p>
<h3>Source maps support</h3>
<p>jQuery 1.9 adds the ability to map minified versions of code to the un-minified versions making debugging easier. </p>
<p>This is a welcome addition as often times the errors are tacked away in some minified code. It also means that we can minify our code before deployment which will improve performance.</p>
<p>I am not going to go into details about source maps in this article but their is a very good article titled <a href="http://www.elijahmanor.com/2013/01/the-magic-of-jquery-source-map.html" class="ext-link">The Magic of the jQuery 1.9 Source Map</a><br />
by Elijah Manor that goes into details on how to set up this feature </p>
<h3>Ajax events</h3>
<p>Ajax events must now be attached to the <code>document</code> not the DOM node when using the <code>ajaxStart()</code> method. i.e <span class="code2">$(document).ajaxStart(&#8230;);</span> and not <span class="code2">$(&#8216;#node&#8217;).ajaxStart(&#8230;);</span></p>
<p>The <span class="code2">ajaxStart()</span> method specifies what function to run when the AJAX request starts. For example, let&#8217;s say you had a button on a page that loads some content asynchronously e.g. <span class="code-normal2">$(&#8216;button&#8217;).on(&#8216;click&#8217;, function(){ $(&#8216;#elem&#8217;).load(&#8216;some_page.html&#8217;) })</span> <br />You can show a pre-loader (animated gif) while the content loads by using the <span class="code2">ajaxStart()</span>method. Something like; <span class="code-normal2">$(&#8216;#elem&#8217;).ajaxStart(function(){ $(this).html(&#8216;&lt;img src=&#8221;preloader.gif&#8221;/&gt;&#8217;); })</span> <br />This will show a animated gif as soon as the request is made, which in turn is replaced by the content once a response is complete.</p>
<h2>To upgrade or not to upgrade</h2>
<p>As is the case for any new library, it&#8217;s advisable to wait for some time before you install, or upgrade to the new iteration. I&#8217;d suggest you wait for a few more weeks while all the issues that may arise are ironed out. </p>
<p>Unlike it&#8217;s predecessors, jQuery 1.9 will not be a straightforward plug and play upgrade because of the aforementioned changes, but the jQuery migrate plugin provides a bridge that will make the process less painful. jQuery is evolving, and soon or later we must/will embrace the change.</p>
<h2>In closing&#8230;</h2>
<p>jQuery 1.9 lays the foundation for the big one, jQuery 2.0 which drops support for IE6, 7 and 8. Now, IE8 is the highest version that you can run on windows XP and there is still a high percentage of windows XP users who see no reason to upgrade to windows 7. This means that developers will continue to support IE8 for a while yet. </p>
<p>Here is a dilemma that is going to face developers; should we have two jQuery code bases for our applications, conditionally loading a jQuery version depending on which OS the user is running? Or are we going to stick to jQuery 1.9 foregoing all the added features in jQuery 2.0? There is a conundrum for you to ponder.</p>
<h2>Useful resources</h2>
<ul>
<li>jQuery 1.9 cdn <input id="cdn" value="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </li>
<li><a href="http://jquery.com/" class="ext-link">Download jQuery 1.9</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://webdevhub.co.uk/whats-new-in-jquery-1-9/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing Modular JavaScript</title>
		<link>http://webdevhub.co.uk/writing-modular-javascript/</link>
		<comments>http://webdevhub.co.uk/writing-modular-javascript/#comments</comments>
		<pubDate>Wed, 06 Feb 2013 11:18:07 +0000</pubDate>
		<dc:creator><![CDATA[Samson Muhangi]]></dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://webdevhub.co.uk/?p=675</guid>
		<description><![CDATA[I will start off by saying that I am no guru when it comes to JavaScript. There are guys who will have me for breakfast when it comes to this stuff, as they were in this business way before I knew what a span was. That said, I am starting to get cosy enough with &#8230; <a href="http://webdevhub.co.uk/writing-modular-javascript/">Read more <span class="meta-nav">&#62;&#62;</span></a>]]></description>
				<content:encoded><![CDATA[<div><span><img class="img-media" src="/wp-content/themes/twentyeleven/images/modular.png" alt="LESS" title="Modular JavaScript" /></span></div>
<p>I will start off by saying that I am no guru when it comes to JavaScript. There are guys who will have me for breakfast when it comes to this stuff, as they were in this business way before I knew what a <code>span</code> was. That said, I am starting to get cosy enough with JavaScript to a point where I feel that I can share some of what I have learnt over the past few years. This article is geared towards intermediate JavaScript developers who aspire to becoming better developers. In my quest to becoming a decent developer, I scoured the web for good resources and I feel that it is only right that I give back.</p>
<p>Programmers with a background in languages such as Java and C++ dislike JavaScript because it does not have structure and well, it is a &#8216;weakly typed&#8217; (= no type declarations) programming language. What the detractors don&#8217;t or refuse to see however, is that; because JavaScript does not force a structure on you, this allows expressiveness and imagination. That said, this freedom is often abused by developers who write unreadable and unmaintainable code. To combat this, we can approach coding in a more pragmatic way, by writing our code in a Modular fashion and adopting proven coding techniques, better known as <strong>design patterns</strong>. </p>
<blockquote><p>Design patterns are proven coding techniques that make code readable, scalable and maintainable.</p></blockquote>
<p>There is a plethora of material on design patterns and I give a few links to my favourites in the &#8220;useful resources&#8221; section below.</p>
<p>Modular code is a term that is now prevalent in the JavaScript echelon which simply means; writing your code in sections that are readable, scalable and maintainable. We have all written &#8216;spaghetti&#8217; code due to time constraints or just out of sheer ignorance (we didn&#8217;t know any better). Usually within a few months we can hardly discern our own code, not to mention the mess we leave for people who inherit our code. </p>
<p>Writing Modular JavaScript gives structure to your code, and helps in limiting the number of global variables, which in turn improves the overall performance of your application/website. I particularly like the <strong>object design pattern</strong> when writing Modular code as it makes reading and maintaining code such a breeze. Well, I think it&#8217;s time to get down to the nitty gritty of Modular JavaScript.</p>
<h2>Task at hand</h2>
<p>To demonstrate the concept, let&#8217;s set up a module for a twitter widget that displays the latest tweets from a twitter account on a website. It displays the first 6 tweets and offers a ability to load more tweets by way of a button.</p>
<h2>Our Module</h2>
<p>Let us simply call our module <code>TweetsWidget</code>. Normally, I would use the camel case naming convention for my variables but I will capitalise module names as it makes them stand out. </p>
<h2>Module definition</h2>
<pre class="snippet">

	<span class="var">var</span> TweetsWidget = {}
</pre>
<h2>Configuration</h2>
<p>To make our widget configurable and give the users more leverage we will provide some settings that can be changed to suit the users needs. Our widget module will have methods that perform different tasks. Since these methods might need access to the configurations, we will create a variable <code>c</code> which points to the configuration settings.</p>
<h2>Settings</h2>
<pre class="snippet">
<span class="var">var</span> c,
    TweetsWidget = {
	settings:{
		tweetCount: <span class="snip-val">6</span>,
		tweetsWrapper = <span class="snip-val">$</span>('#our-tweets'),
		moreTweetsBtn = <span class="snip-val">$</span>('#tweets-btn')
	},

	<span class="snip-comment">/*------------</span>
	<span class="snip-comment">| innitialise</span>
	<span class="snip-comment">-------------*/</span>
	<span class="prop">init</span>: function(){
		c = <span class="snip-func">this</span>.settings;
	}
    };
</pre>
<h2>Binding widget events</h2>
<p>Since we are adding a button for users to load more tweets if they so wish, let&#8217;s create a method that handles the <abbr title="User Interface">UI</abbr> events of our widget. Some developers may view this as unnecessary, but I think it makes our code more structured and readable. This will invoke the method that actually does the work. i.e loads more tweets.</p>
<h2>Settings</h2>
<pre class="snippet">
<span class="var">var</span> c,
    TweetsWidget = {
	settings:{
		tweetCount: <span class="snip-val">6</span>,
		tweetsWrapper = <span class="snip-val">$</span>('#our-tweets'),
		moreTweetsBtn = <span class="snip-val">$</span>('#tweets-btn')
	},

	<span class="snip-comment">/*------------</span>
	<span class="snip-comment">| innitialise</span>
	<span class="snip-comment">-------------*/</span>
	<span class="prop">init</span>: function(){
		c = <span class="snip-func">this</span>.settings;
		<span class="snip-func">this</span>.evntHandler();
	},

	<span class="snip-comment">/*---------------</span>
	<span class="snip-comment">| click handler</span>
	<span class="snip-comment">-----------------*/</span>
	<span class="prop">evntHandler</span>: function(){
		c.moreTweetsBtn.on('<span class="method">click</span>', function(){
			TweetsWidget.getMoreTweets(<span class="method">c.tweetCount</span>);
		});
	},

	<span class="snip-comment">/*------------------------------</span>
	<span class="snip-comment">| utility that loads more tweets</span>
	<span class="snip-comment">----------------------------------*/</span>
	<span class="prop">getMoreTweets</span>: function(<span class="method">num</span>){
		<span class="snip-comment">//we use num as a parameter for the number of tweets we want</span>
		<span class="snip-comment">//we probably use some AJAX here to avoid entire page reloads.</span>
	}
   };
</pre>
<p>We will not write the <code>getMoreTweets</code> method as this is only a demonstration of how to structure our code. That&#8217;s it! We now have a module whose job is to handle the loading and displaying of recent tweets onto our site. It is evident that there is no ambiguity as to what the code does, it&#8217;s readable and maintainable. If we decide to augment our module, all we have to do is add another property to <code>TweetsWidget</code> and invoke the method via the <code>init</code> function.</p>
<h2>What next?</h2>
<p>We can now use another script, whose job is to load modules, to call the <code>TweetsWidget</code> module. This script will probably be used as a module loader as it is very likely that we will have more JavaScript on our site. </p>
<h2>Module loader</h2>
<pre class="snippet">

(function(){
	
	<span class="snip-comment">//load tweets widget</span>
	TweetsWidget.init();

	<span class="snip-comment">//load some other module</span>
	AnotherModule.init();

})();
</pre>
<p>This is perfect on small projects. On big projects however, the number of modules can quickly get out of hand which could lead to big performance overheads and slow page load times due to the number of files being loaded. Also, you might not necessarily want some of the modules loaded into every page on your site. </p>
<p>To combat this, we can use a <strong>Asynchronous Module Definition</strong> loader (<abbr title="Asynchronous Module Definition">AMD</abbr>). <a href="http://requirejs.org/"class="ext-link">RequireJS</a> is a very popular script that handles module loading very well. I am not going to go into details about AMD or RequireJS as they both deserve their own forum. I will nonetheless encourage you to check out the &#8216;useful resources&#8217; section below. </p>
<h2>Summary</h2>
<p>The benefits of writing Modular JavaScript are clear for all to see. Some people might argue that loading several JavaScript files increases page load times. I would say that this is becoming less of a problem with modern browsers that have faster rendering and JavaScript engines. Another solution to the problem is to load your files asynchronously using tools such as RequireJS. Among other useful features that RequireJS brings to the table, is a build tool that amalgamates all your files and minifies them before serving them to the browser. </p>
<p>Writing JavaScript in a Modular fashion will also go a long way in nullifying the perception that JavaScript is messy, unreadable and unmanageable. If we all as developers get onto the Modular JavaScript bandwagon, then maybe, just maybe, all the naysayers might come along for the ride. </p>
<h2>Useful resources</h2>
<ul>
<li><a href="http://requirejs.org/docs/whyamd.html" class="ext-link">Why AMD?</a><span class="website"> website</span></li>
<li><a href="http://addyosmani.com/resources/essentialjsdesignpatterns/book/" class="ext-link">Learn Javascript Design Patterns</a><span class="e-book"> e-book</span></li>
<li><a href="http://requirejs.org/"class="ext-link">RequireJS</a><span class="website"> website</span></li>
<li><a href="http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate" class="ext-link">JavaScript Patterns by Stoyan Stefanov</a><span class="book"> book</span></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://webdevhub.co.uk/writing-modular-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Do more with LESS</title>
		<link>http://webdevhub.co.uk/do-more-with-less/</link>
		<comments>http://webdevhub.co.uk/do-more-with-less/#comments</comments>
		<pubDate>Tue, 15 Jan 2013 09:11:56 +0000</pubDate>
		<dc:creator><![CDATA[Samson Muhangi]]></dc:creator>
				<category><![CDATA[CSS3]]></category>

		<guid isPermaLink="false">http://webdevhub.co.uk/?p=570</guid>
		<description><![CDATA[If you are like me, you have probably wondered why hitherto in CSS, we have not been able to use variables, functions and other general programming good practices given its verbose nature. Most developers that write CSS are familiar with programming principles and wouldn&#8217;t it be great if these could be applied to CSS? Well, &#8230; <a href="http://webdevhub.co.uk/do-more-with-less/">Read more <span class="meta-nav">&#62;&#62;</span></a>]]></description>
				<content:encoded><![CDATA[<div><span><img class="img-media" src="/wp-content/themes/twentyeleven/images/less-css-logo.png" alt="LESS" title="LESS" /></span></div>
<p>If you are like me, you have probably wondered why hitherto in <abbr title="Cascading Style Sheets">CSS</abbr>,  we have not been able to use variables, functions and other general programming good practices given its verbose nature. Most developers that write CSS are familiar with programming principles and wouldn&#8217;t it be great if these could be applied to CSS? Well, we are in luck, say hello to <abbr title="Less CSS">LESS</abbr>.</p>
<h2>What is LESS?</h2>
<p>LESS is a syntax or preprocessor that takes CSS and applies familiar programming principles such as <em>variables</em>, <em>functions</em>, <em>mixins</em> (more about this little number later) and <em>nesting</em>. What we get, is a smarter and dynamic language for writing CSS. You can take either the client-side or server-side approach when implementing LESS. When using the client-side approach, LESS is interpreted into regular CSS by way of JavaScript at runtime.  </p>
<p>The ability to declare variables for example, gives us a more efficient way of changing values after the fact. For instance, if we decide that we now want to change a color used on the site from cyan to hot pink, we do not have to scour the stylesheet for all the instances of cyan. All we need to do is change it at source i.e where the variable is declared. LESS also brings the benefits of utility functions to CSS, a much welcome addition. LESS derives its name from yes, you guessed it; the ability to write less CSS.</p>
<h2>How easy is it to get the ball rolling?</h2>
<p>Compared to the other preprocessors, compass/SASS and Stylus, both of which need Ruby installed on your machine, LESS is child&#8217;s play so to speak, when it comes to implementation for client-side usage. It takes nothing but a couple of steps to get up and running.</p>
<p><strong>Step 1</strong><br />
Create a <span class="code-normal">.less</span> file and link to it from the <code>head</code> section like so: <span class="code-normal2">&lt;link type=&#8221;text/css&#8221; rel=&#8221;stylesheet/less&#8221; href=&#8221;main.less&#8221; /&gt;</span></p>
<p><strong>Step 2</strong><br />
For client-side usage, head off to <a href="http://lesscss.org" class="ext-link">lesscss.org</a>, download <span class="code-normal">less.js</span> and reference it from the <code>head</code> section.<br />
<span class="code-normal2">&lt;script src=&#8221;js/less.js&#8221;&gt;&lt;/script&gt;</span></p>
<p><strong>Important</strong>: It&#8217;s imperative that the stylesheet reference is placed above the Javascript script tag. </p>
<p>And that&#8217;s it. You are now ready to start writing LESS. </p>
<p>If you are however looking for some flexibility, you can configure certain aspects and functionality on the LESS global object. You can find out more about configuration in the <a href="http://lesscss.org" class="ext-link">documentation</a>.</p>
<p>For the server-side approach, it is highly recommended that you use <abbr title="Node Package Manager">npm</abbr>. <a href="http://nodejs.org" class="ext-link">Node.js</a> (a server-side JavaScript interpreter) provides a <a href"https://npmjs.org/" class="ext-link">package manager</a>(npm) that runs through the command-line tool. This is the best way to install and use LESS server-side. I am not going to get into details on the command-line approach, but if you are interested, there is a very good wiki on the subject on <a href="https://github.com/cloudhead/less.js/wiki/Command-Line-use-of-LESS" class="ext-link">github</a>. </p>
<h2>Now the syntax</h2>
<p>The LESS syntax/language is very similar to CSS. All LESS and other preprocessors do is add cool features to CSS. By way of example, I will demonstrate some of these features.</p>
<h3>Variables</h3>
<p>LESS variables are prefixed with a @ sign and once declared can be referenced throughout the stylesheet. We can use variables for any CSS values e.g colors, text or numbers. This is an efficient way of storing values as we only have to change them in one place as opposed to regular CSS where one has to scan through the stylesheet for all instances of the value in question.</p>
<h2>LESS</h2>
<pre class="snippet">
&nbsp;&nbsp;&nbsp;@bgColor:<span class="snip-val">#c0ffee;</span>
&nbsp;&nbsp;&nbsp;@fontSize:<span class="snip-val">12px;</span>
&nbsp;&nbsp;&nbsp;@borderStyle:<span class="snip-val">dashed;</span>
&nbsp;&nbsp;&nbsp;@borderColor:<span class="snip-val">#f0f;</span>
&nbsp;&nbsp;&nbsp;div{ 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;width:<span class="snip-val">150px;</span> 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;height:<span class="snip-val">150px;</span> 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;background:<span class="snip-val">@bgColor;</span> 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;border:<span class="snip-val">1px @borderStyle @borderColor;</span> 
&nbsp;&nbsp;&nbsp;}</pre>
<p>here is the CSS after compilation:</p>
<h2>COMPILED CSS</h2>
<pre class="snippet">&nbsp;&nbsp;&nbsp;div{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;width:<span class="snip-val">150px;</span>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;height:<span class="snip-val">150px;</span>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;background:<span class="snip-val">#c0ffee;</span>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;border:<span class="snip-val">1px dashed #f0f;</span>
 }</pre>
<p>So, if we decide to change <code>#c0ffee</code> to <code>#bada55</code>, we only have to change the value of <code>@bgColor</code>(declaration) and all the instances of <code>@bgColor</code> within the stylesheet will be dynamically updated.</p>
<h3>Mixins</h3>
<p>Mixins are akin to functions in that they are blocks of code that can be invoked anywhere within the stylesheet. They can accept arguments similar to functions in other programming languages &#8211; say, JavaScript. A very good use case scenario is vendor prefixes. In many cases we find ourselves repeating vendor prefixes for features that are not yet supported in some browsers. </p>
<p>Using a mixin can make this more dynamic and efficient as I demonstrate below. </p>
<h2>LESS</h2>
<pre class="snippet">.border-radius(<span class="snip-func">values</span>){ 
-webkit-border-radius:<span class="snip-val">$values;</span> 
-moz-border-radius:<span class="snip-val">$values;</span> 
&nbsp;&nbsp;&nbsp;border-radius:<span class="snip-val">$values;</span> 
}
div { .border-radius(<span class="snip-func">10px</span>); }</pre>
<p>Now whenever we want to add rounded corners to an element, we just call our new border radius mixin and pass in a value. Here is the *compiled CSS;</p>
<h2>COMPILED CSS</h2>
<pre class="snippet">
&nbsp;&nbsp;&nbsp;div{ 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-webkit-border-radius:<span class="snip-val">10px;</span> 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-moz-border-radius:<span class="snip-val">10px;</span>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;border-radius:<span class="snip-val">10px;</span>
&nbsp;&nbsp;&nbsp;}</pre>
<p>Imagine what we can do with this feature! For instance you could create a mixin with default values or pass your desired value at invocation. Here is another example;<br />
<span class="code-normal2"><span class="snip-comment">//create a mixin that accepts an optional background color</span><br />
.flag(@bgColor:&#8221;#cf0&#8243;){ background-color:@bgColor }<br />
<span class="snip-comment">//apply styles from the mixin above </span><br />
.highlight { .flag(); border:1px solid red; }<br />
<span class="snip-comment">//or pass in a different color</span><br />
.highlight2 { .flag(&#8216;#333&#8217;); }<br />
</span></p>
<h3>Color functions</h3>
<p>Color functions are some of the built-in functions that come with LESS. They give us the ability to create variations of a single color. A good use case scenario is when you want to create gradients or hover colors. In the snippet below, I dynamically generate a link hover color using the <em>darker</em> color function;</p>
<h2>LESS color function</h2>
<pre class="snippet">@color:<span class="snip-val">#c0ffee;</span>
a { color:<span class="snip-val">@color;</span> }
a:hover { color:<span class="snip-val">darken($color, 25%);</span> <span class="snip-comment">//the hover link will compile to 25% darker than @color</span> } </pre>
<p>Other color functions include;</p>
<ul>
<li><strong>lighten</strong> &#8211; lightens @color by a specified percentage </li>
<li><strong>saturate</strong> &#8211; compiles to a more saturated color</li>
<li><strong>desaturate</strong> &#8211; does the opposite of saturate</li>
<li><strong>mix</strong> &#8211;  returns a mix of two colors</li>
</ul>
<p>LESS has many more built functions that can do much more. Refer to the <a href="http://lesscss.org/#-functions" class="ext-link">LESS documentation</a> for more.</p>
<h3>Nesting</h3>
<p>If you are familiar with the CSS cascading principle, you will know that it leads to a lot of repetition. Say for example;<br />
<span class="code-normal2">#main { color:<span class="snip-val">#f0f;</span> }<br />
#main .first { color:<span class="snip-val">#c0ffee;</span> }<br />
#main a { text-decoration:<span class="snip-val">none;</span> }<br />
#main a:hover { tex-decoration:<span class="snip-val">underline;</span> }<br />
</span></p>
<p>LESS alleviates this repetitiveness by introducing nesting. We can re-write the above code as follows;</p>
<h2>Nesting in LESS</h2>
<pre class="snippet">
#main { 
&nbsp;&nbsp;color:<span class="snip-val">#f0f;</span>

&nbsp;&nbsp;.first{
&nbsp;&nbsp;&nbsp;&nbsp;color:<span class="snip-val">#c0ffee;</span>
&nbsp;&nbsp;}
&nbsp;&nbsp;a{
&nbsp;&nbsp;&nbsp;&nbsp;text-decoration:<span class="snip-val">none;</span>
&nbsp;&nbsp;&nbsp;&nbsp;&#038;:hover{ text-decoration:<span class="snip-val">underline;</span> }
&nbsp;&nbsp;}
}
</pre>
<p>Note the use of the ampasand(&#038;) for pseudo classes. The same applies for element type selectors e.g <code>p.warning</code> </p>
<h3>Operations</h3>
<p>Yes, you read right. In LESS you can perform operations on variables and color values. Lets do some simple operations in LESS;</p>
<h2>LESS Operations</h2>
<pre class="snippet">
@width: <span class="snip-val">150px;</span>
@height: <span class="snip-val">50px;</span>
div { 
&nbsp;&nbsp;width:<span class="snip-val">(@width + 5); </span><span class="snip-comment">//this will evaluate to 155px</span>   
&nbsp;&nbsp;height:<span class="snip-val">(@height * 2); </span><span class="snip-comment">//this will evaluate to 100px</span>
}
</pre>
<h2>Summary</h2>
<p>LESS is picking up traction in the web development community primarily because, by adding useful features such as variables and functions, LESS saves time. Try it in your next project and you will not be disappointed. As I mentioned earlier, Compass/SASS and Stylus are the other CSS preprocessors at our disposal but I think LESS is by the far the easiest to work with.</p>
<p><strong>A word of caution:</strong> Compiling client-side has a performance overhead, especially on big projects. It&#8217;s recommended that you either use caching on compile server-side.    </p>
<p><strong>Note:</strong> I should point out that I have used the term &#8216;compile&#8217; loosely for emphasis. Strictly speaking JavaScript does not compile, it interprets.</p>
<h2>Useful resources</h2>
<ul>
<li><a href="http://lesscss.org" class="ext-link">lesscss.org</a> </li>
<li><a href="http://css-tricks.com/video-screencasts/88-intro-to-compass-sass/" class="ext-link">Introduction to Compass/SASS</a></li>
<li><a href="http://lesselements.com" class="ext-link">Elements.less</a> &#8211;  a set of ready mixins that augment LESS .</li>
<li><a href="http://getpreboot.com/" class="ext-link"> preboot.less</a> &#8211; &#8211; a collection of very handy mixins include grids.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://webdevhub.co.uk/do-more-with-less/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Saving form data using the localStorage API</title>
		<link>http://webdevhub.co.uk/saving-form-data-using-the-localstorage-api/</link>
		<comments>http://webdevhub.co.uk/saving-form-data-using-the-localstorage-api/#comments</comments>
		<pubDate>Sat, 01 Dec 2012 15:27:22 +0000</pubDate>
		<dc:creator><![CDATA[Samson Muhangi]]></dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://webdevhub.co.uk/?p=460</guid>
		<description><![CDATA[Here is a scenario that we can all relate to; You are filling in a long form and half way through, you inadvertently close the tab/window or worse still your laptop decides to crash. &#8216;Argh!, I was half way through that form, now I have to start again?&#8217; comes to mind. Well, fret no more. &#8230; <a href="http://webdevhub.co.uk/saving-form-data-using-the-localstorage-api/">Read more <span class="meta-nav">&#62;&#62;</span></a>]]></description>
				<content:encoded><![CDATA[<div><span><img class="img-media" src="/wp-content/themes/twentyeleven/images/html5_local_storage.jpg" alt="HTML5 local storage" title="HTML5 Local storage" /></span></div>
<p>Here is a scenario that we can all relate to; You are filling in a long form and half way through, you inadvertently close the tab/window or worse still your laptop decides to crash. &#8216;Argh!, I was half way through that form, now I have to start again?&#8217; comes to mind. Well, fret no more. Thanks to the localStorage <abbr title="Application Programming Interface">API</abbr> we can store form values (and more) on the fly so that in the event that the above happens, the values already entered will still be in browser memory. Storing persisting data has never been easier, and it lends itself well to enhancing user experience. I can here you say, but isn&#8217;t that a cookie? No way Jose! Sit back, relax and enjoy the ride!</p>
<h2>What is this localStorage API thingy?</h2>
<p>Simply put, <code>localStorage</code> is a JS API (commonly referred to as part of the HTML5 spec) that facilitates data storage in the browser. This is in form of key/value pairs that persist even when the user navigates away from the page. Persistence is where the similarity between <code>localStorage</code> and cookies ends. Not to be presumptuous, <span class="indent-me"><strong>key</strong> &#8211; A name for a value to be stored.</span> <span class="indent-me"><strong>value</strong> &#8211; The value stored.</span> Unlike Cookies,</p>
<ul>
<li>localStorage does not expire, Cookies do</li>
<li>the localStorage API recommends up to 5MB, Cookies are small(approx. 4kb) </li>
<li>The localStorage API is very easy to work with as it&#8217;s simply a JavaScript object made up of key/value pairs, Cookies are messy NOTE: even if an object, the localStorage object can only store simple data types i.e strings, numbers and floating points.</li>
<li>localStorage is not sent in HTTP requests, Cookies are. This adds an overhead to your web application as unnecessary requests are made to the server.</li>
</ul>
<p><code>localStorage</code> can be accessed via the global <code>window</code> object and is supported in the latest iterations of all the major browsers, IE included. As a matter of fact <code>localStorage</code> is supported as of IE8. To test for localStorage support, simply let <a href="modernizr" class="ext-link">Modernizr</a> (you should be using it) do the detection for you, here is how;<br />
<span class="code-normal2">if(Modernizr.localstorage){<br />
&nbsp;&nbsp;&nbsp;//browser supports localStorage<br />
}else{<br />
&nbsp;&nbsp;&nbsp;//browser does NOT support localStorage<br />
}</span></p>
<p>You however do not have to use Modernizr to test for localStorage support. You can simply check if the <code>window</code> object has the localStorage property;<br />
<span class="code-normal2">if(window.localStorage){<br />
&nbsp;&nbsp;&nbsp;//browser supports localStorage<br />
}else{<br />
&nbsp;&nbsp;&nbsp;//browser does NOT support localStorage<br />
}</span><br />
but then again, <code>Modernizr</code> aids the detection of all the other cool progressive enhancement features, so why not take advantage.<br />
Crash course over!</p>
<h2>So how do I use this nice API to save form data?</h2>
<p>As I alluded to above, the localStorage API makes working with persistent data a breeze. It&#8217;s also very easy to implement. So without further ado, here we go;</p>
<h2>localStorage implementation</h2>
<pre class="snippet">if(Modernizr.localstorage){   
    <span class="snip-comment">//browser supports localstorage</span>
    <span class="jq">$</span>(<span class="snip-func">function</span>(){

    	<span class="snip-comment">//lets store input field data in a field on blur.</span>
    	$(<span class="snip-val">'form'</span>).<span class="method">on</span>(<span class="snip-val">'blur'</span>, <span class="snip-val">'input'</span>, <span class="snip-func">function</span>(){
    		<span class="snip-comment">//set a flag to indicate that we have saved data! </span>
    		localStorage.<span class="method">setItem</span>(<span class="snip-val">'flag'</span>,<span class="snip-val">'formData'</span>);

    		<span class="snip-comment">//lets serialize the form data using jQuery's serializeArray()</span>
    		<span class="var-name">var</span> data = $(<span class="snip-val">'form'</span>).<span class="method">serializeArray</span>();

    		<span class="snip-comment">//lets loop through the data and save the input data</span> 
    		<span class="jq">$</span>.<span class="method">each</span>(<span class="snip-val">data</span>, <span class="snip-func">function</span>(i, obj){
    			localStorage.<span class="method">setItem</span>(<span class="snip-val">obj.name</span>, <span class="snip-val">obj.value</span>);
    		});
    	});

    	<span class="snip-comment">/*--------------------------------------------------------------
    	<span class="snip-comment">| if saved form data exists set input field values. </span>
    	<span class="snip-comment">| Note: this will naturally run before the above code </span>
    	<span class="snip-comment">| which is only triggered on the blur event.</span>
    	<span class="snip-comment">--------------------------------------------------------------*/</span>
    	if (localStorage.<span class="method">getItem</span>(<span class="snip-val">'flag'</span>)){
    		<span class="var-name">var</span> data = $(<span class="snip-val">'form'</span>).<span class="method">serializeArray</span>();

    		<span class="jq">$</span>.<span class="method">each</span>(<span class="snip-val">data</span>, <span class="snip-func">function</span>(i, obj){
    			<span class="jq">$</span>(<span class="snip-val">"[name='"+obj.name+"']"</span>).<span class="method">val</span>(localStorage.<span class="method">getItem</span>(obj.name));
    		});
    	}
    });

}else{

   <span class="snip-comment">//NO native localStorage support - resort to a fallback eg $.localStorage()</span>

}</pre>
<p>In the above snippet, we test for <code>localStorage</code> support which if successful, and after the DOM is ready, we use the <span class="code-normal">blur</span> event to trigger <code>localStorage</code>, calling the <span class="code-normal">setItem()</span> method in particular. This little number will create key (obj.name), value (obj.value) pairs for all input fields other than the submit button and store these as an array of objects stored in browser memory. We do this by iterating through the serialized form data. In layman talk, every time the user moves away from a field we tell the browser to store the values in the input fields. </p>
<p>Great! We have now stored the data, but how do we then retrieve this data? Before we retrieve the data and populate the respective fields, note that we set a flag if <span class="code-normal">localStorage.setItem()</span> has been invoked on the form data. We can then maybe alert the user that form data was saved last time they filled in the form, but we can also use this flag as a test for presence of saved data. We then serialize the form data so that we can loop through it and set the values of the input fields. Note that instead of invoking the <span class="code-normal">setItem()</span> method, we are now calling upon its sibling <span class="code-normal">getItem()</span>.<em>Voilà</em>! Easy as pie.</p>
<p>Being the nice developers that we are, we can also provide a way for the user to clear the form fields if they so wish, by simply adding a button to clear input data. The click event handler for the button will be something akin to;</p>
<p><span class="code-normal">$(&#8216;#clear-btn&#8217;).on(&#8216;click&#8217;, function(){ localStorage.setItem(&#8216;flag&#8217;,&#8221;) })</span></p>
<p>On clicking the &#8216;clear button&#8217; the value of the flag will be set to empty string which is a <span class="code-normal">falsey</span> value. Consequently, when the user reloads the page, the code that sets the input values to the stored data will not execute/run.</p>
<h2>Browser support</h2>
<p><img src="/wp-content/themes/twentyeleven/images/local_storage.png" /> </p>
<h2>Summary</h2>
<p>The fact that the <code>localStorage</code> interface is a lot easier to use compared to the now ageing cookies, is the reason this API has had rapid adoption by many in the development community. There are many applications for <code>localStorage</code> but I have used persisting form data as a way of whetting your appetite and I implore you to explore this cool API further. Hopefully, this will make storing and working with client-side data a tad bit easier. </p>
<p>That said, <code>localStorage</code> should be used judiciously and users should always be made aware that their data is being stored albeit to improve user experience.  Don&#8217;t forget those disclaimers!</p>
<h2>Useful resources</h2>
<ul>
<li><a class="ext-link" href="http://diveintohtml5.info/storage.html">The past, present, and future of local storage</a>&#8211; by Mark Pilgrim</li>
<li><a class="ext-link" href="http://www.jquerysdk.com/api/jQuery.localStorage">jQuery localStorage</a></li>
<li><a class="ext-link" href="http://www.andismith.com/blog/2012/04/comply-with-eu-cookie-law/">comply with EU cookie law</a> &#8211; by Andi Smith</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://webdevhub.co.uk/saving-form-data-using-the-localstorage-api/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PictureFill &#8211; A responsive images technique</title>
		<link>http://webdevhub.co.uk/picturefill-a-responsive-images-technique/</link>
		<comments>http://webdevhub.co.uk/picturefill-a-responsive-images-technique/#comments</comments>
		<pubDate>Mon, 05 Nov 2012 22:28:06 +0000</pubDate>
		<dc:creator><![CDATA[Samson Muhangi]]></dc:creator>
				<category><![CDATA[CSS3]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Mobile]]></category>
		<category><![CDATA[Responsive Web Design]]></category>
		<category><![CDATA[RWD]]></category>

		<guid isPermaLink="false">http://webdevhub.co.uk/?p=432</guid>
		<description><![CDATA[If your web application takes more than 3 seconds to load, you will soon get a call from the the latency police to explain yourself. Users expect snappy applications otherwise they will move on to the next website with better user experience. For businesses, you can not overstate the importance of fast applications as this &#8230; <a href="http://webdevhub.co.uk/picturefill-a-responsive-images-technique/">Read more <span class="meta-nav">&#62;&#62;</span></a>]]></description>
				<content:encoded><![CDATA[<div><span><img class="img-media" src="/wp-content/themes/twentyeleven/images/resp_imgs_thumb.jpg" alt="Responsive Images" title="Responsive Images" /></span></div>
<p>If your web application takes more than 3 seconds to load, you will soon get a call from the the latency police to explain yourself. Users expect snappy applications otherwise they will move on to the next website with better user experience. For businesses, you can not overstate the importance of fast applications as this could be the difference between success and failure. One of the reasons most web pages take a long time to load is the amount of requests made by the browser and the size of the files that need to be pre-loaded. Reducing the amount of requests, is at the core of improving user experience.</p>
<p>Recently in my day job, I was assigned a task of creating a prototype to demonstrate responsive images. Fishing rod in hand I headed off fishing for some new techniques. There is no shortage of server and client side techniques but I settled for PictureFill.</p>
<h2>What is PictureFill?</h2>
<p>PictureFill is a responsive image technique devised by <a class="ext-link" href="http://www.w3.org/community/respimg/2012/03/15/polyfilling-picture-without-the-overhead/">Scott Jehl</a> that makes use of the proposed <code>picture</code> element and <a href="http://webdevhub.co.uk/media-queries-and-responsive-web-design/" title="Media Queries" target="_blank">media queries</a> to serve images based on browser window size.</p>
<h2>How does it work?</h2>
<p>An <code>img</code> element is created on the fly using JavaScript based on the source and media query specified within the picture element. This prevents unnecessary overheads that are otherwise incurred by pre-loading large files, especially on small or low speed devices.</p>
<h2>Implementation &#8211; Some code please!</h2>
<p>Head off to the <a class="link-ext" href="https://github.com/scottjehl/picturefill" title="pictureFill on Github" target="_blank">Github code repository</a> and download the code files. The code is very well documented and includes examples. I will nonetheless give a quick run down on the html markup.</p>
<h2>PictureFill HTML markup</h2>
<pre class="snippet">
&lt;<span class="snip-elmnt">picture</span> <span class="snip-attr">data-picture</span> data-alt=<span class="snip-val">"big pebbles"</span>&gt;
  &lt;<span class="snip-elmnt">source</span> data-src=<span class="snip-val">"img/pebbles_small.jpg"</span>&gt;
  &lt;<span class="snip-elmnt">source</span> data-src=<span class="snip-val">"img/pebbles_medium.jpg"</span> data-media=<span class="snip-val">"(min-width: 400px)"</span>&gt;
  &lt;<span class="snip-elmnt">source</span> data-src=<span class="snip-val">"img/pebbles_large.jpg"</span> data-media=<span class="snip-val">"(min-width: 800px)"</span>&gt;
  &lt;<span class="snip-elmnt">source</span> data-src=<span class="snip-val">"img/pebbles_extralarge.jpg"</span> data-media=<span class="snip-val">"(min-width: 1000px)"</span>&gt;

  <span class="snip-comment">&lt;!-- Fallback if no JS --&gt;</span>
    &lt;noscript&gt;
      &lt;img src=<span class="snip-val">"img/small.jpg"</span> alt=<span class="snip-val">"big pebbles"</span>&gt;
    &lt;/noscript&gt;
&lt;/<span class="snip-elmnt">picture</span>&gt;</pre>
<p>In the snippet above, I use the <code>picture</code> element to nest all the various image sources using, well the <code>source</code> element. Note that I also specify the screen resolutions using media queries passed as values for the <code>data-media</code> attribute. The beauty here is the ability to cater for as many screen resolutions as you want. </p>
<p>For users with JavaScript disabled, we have a fallback image which is wrapped in <code>noscript</code> tags. This piece of code will not be executed by browsers running JavaScript. </p>
<p>Well as usually, IE demands special treatment. Using IE conditional comments we can provide a one-size-for-all image for IE8 and below as Media Queries are not supported here. For example if I wanted to serve the medium image to IE8 and below, I can nest the following inside the picture element:<br />
<span class="code-normal2">&lt;!&#8211;[if (lt IE 9) &#038; (!IEMobile)]&gt;<br />
 &nbsp;&nbsp;&lt;source data-src=&#8221;img/thumbs/pebbles_medium_thumb.jpg&#8221;&gt;&lt;/div&gt;<br />
&lt;![endif]&#8211;&gt;</span></p>
<p>If you are understandably apprehensive about using the <code>picture</code> element as it&#8217;s still in draft status with the w3c, you can replace the <code>picture</code> and <code>source</code> tags with the <code>div</code> element. Remember however to make the switch in the JavaScript as well i.e replace all the <code>picture</code> instances with <code>div</code>. My take on standards is that; they do not really mean that much if the browsers do not implement the module in question. After all users are not concerned about whether the your code is legal or not. That&#8217;s not to say that we should totally disregard semantics and standards. Word is that a few browsers have began implementing the picture/source model.  </p>
<h2>Summary</h2>
<p>To many this might seem a very involved workaround to a problem that does not yet have a standardized solution, but until a fix comes along, this is a semantic workaround for the purist. As I mentioned earlier, there is no shortage of polyfills and workarounds in the web dev community, but this by far gets my vote.</p>
<h2>Useful resources</h2>
<ul>
<li><a class="ext-link" href="http://adaptive-images.com/">Adaptive Images</a> &#8211; a server side responsive images technique</li>
<li><a class="ext-link" href="https://github.com/teleject/hisrc">HiSRC</a> &#8211; a jQuery plugin for responsive images</li>
<li><a class="ext-link" href="http://www.sencha.com/products/io/">Senchia.IO</a> &#8211; cloud based service for mobile development.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://webdevhub.co.uk/picturefill-a-responsive-images-technique/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Chrome Frame turbo charges Internet Explorer</title>
		<link>http://webdevhub.co.uk/chrome-frame-turbo-charges-internet-explorer/</link>
		<comments>http://webdevhub.co.uk/chrome-frame-turbo-charges-internet-explorer/#comments</comments>
		<pubDate>Mon, 15 Oct 2012 20:06:31 +0000</pubDate>
		<dc:creator><![CDATA[Samson Muhangi]]></dc:creator>
				<category><![CDATA[CSS3]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Chrome Frame]]></category>
		<category><![CDATA[Internet Explorer]]></category>

		<guid isPermaLink="false">http://webdevhub.co.uk/?p=357</guid>
		<description><![CDATA[Internet Explorer (IE) has a rather unfashionable habit of showing up to the CSS3 and HTML5 party late. Someone ought to tell Microsoft that their browser has caused many a heartache and angst amongst designers and developers who strive for equal user experience for all mankind irrespective of their browser of choice. Rant over! Let &#8230; <a href="http://webdevhub.co.uk/chrome-frame-turbo-charges-internet-explorer/">Read more <span class="meta-nav">&#62;&#62;</span></a>]]></description>
				<content:encoded><![CDATA[<div><span><img class="img-media" src="/wp-content/themes/twentyeleven/images/chrome_frame.jpg" alt="Media Queries" title="Chrome Frame" /></span></div>
<p>Internet Explorer (IE) has a rather unfashionable habit of showing up to the CSS3 and HTML5 party late. Someone ought to tell Microsoft that their browser has caused many a heartache and angst amongst designers and developers who strive for equal user experience for all mankind irrespective of their browser of choice. Rant over! </p>
<p>Let us focus on people that are opting into the future and are ready to embrace new web technologies, moreover <a href="https://developers.google.com/chrome/chrome-frame/" class="ext-link" title="Chrome Frame" target="_blank">Chrome Frame</a> has now been stable since 2010. In an effort to solve the aforementioned annoyance, a few people at Google got together and came up with a rather canny solution; wrap IE in Chrome&#8217;s clothing. And Chrome Frame was born. </p>
<h2>What is Chrome Frame and why?</h2>
<p>Chrome Frame (GCF) is a plug-in that brings new web technologies to IE. As of writing, technologies such as <code>websockets</code>, and <code>canvas</code> are not supported in IE8 and below. Chrome Frame alleviates this problem. GCF not only brings with it all the good CSS3 and HTML5 features that are otherwise not yet supported by Internet Explorer, it brings Chromes&#8217; JavaScript V8 rendering engine which provides better performance, at least in IE8 and below. </p>
<p>This means developers and designers can invest the time otherwise spent fixing and adapting web apps to IE or worse still curtailing functionality and <abbr title="User Experience">UX</abbr> for IE users, to developing rich applications.</p>
<p>Chrome Frame is also a saving grace for users that are forevermore doomed to legacy IE because their machines are not running the Windows7 <abbr title="Operating System">OS</abbr> and consequently cannot upgrade to IE9+ </p>
<h2>Tapping into Chrome Frame</h2>
<p>Simply adding the <code>http-equiv</code> meta tag in the head section of your document, activates Chrome Frame in IE if the plug in is installed. Browsers that do not understand this tag will simply ignore it. The tag is as follows:<br />
<span class="code-normal2">&lt;meta http-equiv=&#8221;X-UA-Compatible&#8221; content=&#8221;IE=edge,chrome=1&#8243;&gt;</span><br />
The part to pay attention to is the <em>content</em> attribute. <code>IE=edge</code> will coerce the browser to the latest rendering mode installed if the user or browser inadvertently switches to a older version. <code>chrome=1</code> as you might gather enables Chrome Frame. You can also load Chrome Frame conditionally. Say you only want to activate it for users in IE7 and below, you would add <code>chrome=IE7</code> in place of <code>chrome=1</code>.</p>
<h2>What if the user does not have Chrome Frame installed?</h2>
<p>Well, the user can either do a manual install by simply visiting <em>http://www.google.com/chromeframe</em> or as I demonstrate further below we can add a script that will prompt the user to install the plug in if it is not present. </p>
<p>The beauty of Chrome Frame is that the user does not need administrative rights to install the plugin. Simply append <code>?user=true</code> to http://www.google.com/ and you are off and running. </p>
<h2>Implementing the detection script</h2>
<p>In addition to the http-equiv meta tag discussed above, we can add the following script at the bottom (or head section) of our page:</p>
<h2>Chrome Frame detection</h2>
<pre class="snippet">&lt;!--[if lt IE 9 ]&gt;
    &lt;<span class="snip-elmnt">script</span> src=<span class="snip-val">"//ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"</span>&gt;&lt;/<span class="snip-elmnt">script</span>&gt;
    &lt;<span class="snip-elmnt">script</span>&gt;window.<span class="method">attachEvent</span>(<span class="snip-val">'onload'</span>,<span class="snip-func">function</span>(){CFInstall.<span class="method">check</span>({mode:<span class="snip-val">'overlay'</span>})})&lt;/<span class="snip-elmnt">script</span>&gt;
  &lt;![endif]--&gt;</pre>
<p>The snippet above is a Chrome Frame detection and install script that will run if the user is viewing your site in IE8 or below. A gentle prompt in form of an overlay page (not a popup) will be displayed to the user. It is really that simple. Note that the <code>CFInstall.check()</code> method is at the heart of this script and takes several properties e.g,</p>
<ul>
<li><span class="code-normal3">cssText: </span>This is optional and allows you to style the prompt <code>iFrame</code> with your custom styles</li>
<li><span class="code-normal3">onmissing: </span>You can specify a custom callback function if GCF is missing</li>
</ul>
<p>For a definitive list, visit the <a href="http://www.chromium.org/developers/how-tos/chrome-frame-getting-started" title="GCF developer guide" target="_blank" class="ext-link">Chrome Frame developer guide</a>.</p>
<p>To DEMONSTRATE, I have put together a <a href="/chrome-frame-demo" title="Chrome Frame demo" target="_blank" class="ext-link">simple canvas page</a> and if you run it in IE8 or below and have Chrome Frame installed, you will see my Picaso-esque canvas drawing. Conversely, if you do not have Chrome Frame installed, you will not see that beauty. You will however be presented with an in-line dialog (not the obtrusive popup) to install Chrome Frame. Canvas is just one feature that IE8 and its older siblings do not support, there are many more where that came from. </p>
<h2>Summary</h2>
<p>Many big corporations and organisations are very reluctant to update to newer browsers citing financial implications to their IT departments and security risks associated with new software that has not been fully tested. These are all plausible reasons but they also hinder advancement in web technology. </p>
<p>Google Chrome Frame is an alternative and is a testament to Google&#8217;s enthusiasm and desire to move the web forward. Because IE has a big piece of the user pie but painfully slow at implementing the new web technologies, it cannot be taken lightly and efforts have to be made to drag it along into the future. For users who have made the wise move away from using IE as their primary browser, but have IE dependent applications, there are solutions such as <a href="https://chrome.google.com/webstore/detail/ie-tab/hehijbfgiekmjfkfjpbkbammjbdenadd" title="IE tab" target="_blank" class="ext-link">IE-tab</a> that emulate IE in other browsers. </p>
<h2>Useful resources</h2>
<ul>
<li><a class="ext-link" href="http://www.chromium.org/developers/how-tos/chrome-frame-getting-started" title="Chrome Frame - Developer guide" target="_blank">Chrome Frame getting started guide</a></li>
<li><a class="ext-link" href="https://developers.google.com/chrome/chrome-frame/">Google Chrome Frame</a></li>
<li><a class="ext-link" href="http://www.google.com/intl/en/chrome/business/browser/chromeframe.html" title="download Chrome Frame" target="_blank">Download Chrome Frame</a>
</li>
<li><a class="ext-link" href="https://chrome.google.com/webstore/detail/ie-tab/hehijbfgiekmjfkfjpbkbammjbdenadd" title="Downlaod IE-tab" target="_blank">Download IE-tab</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://webdevhub.co.uk/chrome-frame-turbo-charges-internet-explorer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
