<?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>SitePoint &#187; Tech</title> <atom:link href="http://www.sitepoint.com/category/tech/feed/" rel="self" type="application/rss+xml" /><link>http://www.sitepoint.com</link> <description>News, opinion, and fresh thinking for web developers and designers. The official podcast of sitepoint.com.</description> <lastBuildDate>Fri, 10 Feb 2012 05:21:56 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.2.1</generator> <item><title>What&#8217;s New in Chrome 17</title><link>http://www.sitepoint.com/whats-new-in-chrome-17/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=whats-new-in-chrome-17</link> <comments>http://www.sitepoint.com/whats-new-in-chrome-17/#comments</comments> <pubDate>Thu, 09 Feb 2012 15:44:53 +0000</pubDate> <dc:creator>Craig Buckler</dc:creator> <category><![CDATA[Android Discussion]]></category> <category><![CDATA[News & Trends]]></category> <category><![CDATA[Opinion]]></category> <category><![CDATA[chrome]]></category> <category><![CDATA[Google Tutorials & Articles]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=51278</guid> <description><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2011/05/518-chrome-11-50x50.png" class="attachment-thumbnail wp-post-image" alt="518-chrome-11" title="518-chrome-11" />Craig looks at the latest changes to Google's market-dominating web browser.]]></description> <content:encoded><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2011/05/518-chrome-11-50x50.png" class="attachment-thumbnail wp-post-image" alt="518-chrome-11" title="518-chrome-11" /><p></p><p>We&#8217;ve been using Chrome 16 since December 13, 2011. That&#8217;s almost two months &#8212; positively ancient for Google&#8217;s rapidly-updating browser! Like most releases, Chrome 17 provides a number of tweaks. There are fewer major new features than <a
href="http://www.sitepoint.com/firefox-10-whats-new/">Firefox 10</a> but some would argue Chrome requires less polishing.</p><p>Let&#8217;s look at what Chrome 17 has to offer&hellip;</p><h2>Omnibox Pre-loading</h2><p>Type a search term into Chrome&#8217;s address bar <em>(sorry Google &#8212; I still think &#8220;Omnibox&#8221; is a stupid name)</em> and you&#8217;ll notice various suggestions and possible sites. If Chrome&#8217;s confident it&#8217;s read your mind correctly, it&#8217;ll start pre-loading your chosen page. Popular places such Facebook will then appear almost instantaneously although I had less success with other sites.</p><p>User opinion will be mixed. It makes Chrome <em>seem</em> faster but it&#8217;ll sap your bandwidth and could make sites slower by hitting them with unnecessary pre-load requests. I suspect Google has judged it about right &#8212; Chrome only pre-loads when it&#8217;s absolutely certain of your intentions. However, you can switch it off by unchecking &#8220;Predict network actions to improve page load performance&#8221; in <strong>Options</strong> &gt; <strong>Under the Hood</strong>.<div>  <script type='text/javascript'>GA_googleFillSlot("InArticle_728x90_1");</script> </div></p><h2>Malicious File Alerts</h2><p>Chrome will now alert you when a download appears to be malware or some other nasty file. It&#8217;s important to note that Chrome doesn&#8217;t actually scan the file; it verifies the originating server against blacklists and looks for suspicious activity.</p><h2>Override the User Agent</h2><p>It&#8217;s now possible to set a different browser user agent without an add-on. Open the webkit inspector, click the settings cog and check &#8220;Override User Agent&#8221;. It offers various flavors of IE, Firefox, iPhone, iPad and Android or you can enter your own browser string.</p><h2>Add-on Panels</h2><p>Panels are small windows which pop-out to reveal applications which are running all the time but don&#8217;t require their own tab, e.g. music players, chat applications, stock checkers etc. Panels are only available to add-ons and the <a
href="http://code.google.com/chrome/extensions/experimental.devtools.panels.html">API</a> has been updated accordingly.</p><h2>Miscellaneous Updates</h2><p>There are a number of smaller changes you may &#8212; or may not &#8212; like:</p><ul><li>Page zooming has been improved; it goes up to 500% and is more consistent with other browsers.</li><li>Print Preview now appears in a modal dialog rather than its own tab.</li><li>The History tab, <a
href="http://www.sitepoint.com//history/">chrome://history/</a>, has been redesigned. You can filter and remove specific domains.</li><li>A new <a
href="http://www.sitepoint.com//profiler/">chrome://profiler/</a> page provides task profiling and debugging information which could be useful for process-intensive web applications and add-ons.</li><li>HTTP pipelining has been enabled. This permits multiple HTTP requests on a single TCP connection and has been in other browsers for a while.</li><li>There have been a few dozen security fixes and the V8 JavaScript engine has been updated.</li><li>New tab has lost its &#8216;+&#8217; icon. I&#8217;m not convinced that&#8217;s a step forward though?</li></ul><h2>Chrome Arrives on Android</h2><p>Perhaps the biggest news is Google&#8217;s release of Chrome on their Android OS. It&#8217;s a beta application available for Android 4.0 smartphones and tablets. Like Firefox mobile, the browser allows you to seamlessly synchronize your settings, bookmarks and open tabs on all devices. For more information, refer to Google&#8217;s <a
href="http://googleblog.blogspot.com/2012/02/introducing-chrome-for-android.html">Introducing Chrome for Android</a> blog post.</p><p>Google claims they aren&#8217;t interested in dominating the browser market. It makes you wonder how far Chrome could have gone had they made more effort!</p><div
style="text-align:center;padding-bottom:50px;"><div
style="float:left;padding-left:30px;"> <script>GA_googleFillSlot("Edit_300x100_C");</script> </div><div
style="float:right;padding-right:30px;"> <script>GA_googleFillSlot("Edit_300x100_D");</script> </div></div><div
style="clear:both"></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/whats-new-in-chrome-17/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Bringing Cut the Rope to Life in an HTML5 Browser</title><link>http://www.sitepoint.com/bringing-cut-the-rope-to-life-in-an-html5-browser/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=bringing-cut-the-rope-to-life-in-an-html5-browser</link> <comments>http://www.sitepoint.com/bringing-cut-the-rope-to-life-in-an-html5-browser/#comments</comments> <pubDate>Wed, 08 Feb 2012 22:50:01 +0000</pubDate> <dc:creator>Giorgio Sardo</dc:creator> <category><![CDATA[HTML & CSS]]></category> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Web Design Tutorials & Articles]]></category> <category><![CDATA[Web Tech]]></category> <category><![CDATA[HTML5 Dev Center]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=51213</guid> <description><![CDATA[<img
width="50" height="29" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/feature3-50x29.png" class="attachment-thumbnail wp-post-image" alt="feature" title="feature" />Award-winning mobile game Cut the Rope is an immediate favorite for anyone who plays it. It’s as fun as it is adorable. So we had an idea: let’s make this great game available to an even bigger audience by offering it on the web using the power of HTML5. To do this, Microsoft’s Internet Explorer [...]]]></description> <content:encoded><![CDATA[<img
width="50" height="29" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/feature3-50x29.png" class="attachment-thumbnail wp-post-image" alt="feature" title="feature" /><p></p><p>Award-winning mobile game <strong>Cut the Rope</strong> is an immediate favorite for anyone who plays it. It’s as fun as it is adorable. So we had an idea: let’s make this great game available to an even bigger audience by offering it on the web using the power of HTML5.</p><p>To do this, Microsoft’s Internet Explorer team partnered with <a
href="http://zeptolab.com/">ZeptoLab</a> (the creators of the game) and the specialists at <a
href="http://thinkpixellab.com/">Pixel Lab</a> to bring <strong>Cut the Rope</strong> to life in a browser. The end result is an authentic translation of the game for the web, showcasing some of the best that HTML5 has to offer: canvas-rendered graphics, browser-based audio and video, CSS3 styling and the personality of WOFF fonts.</p><p>You can play the HTML5 version of <strong>Cut the Rope</strong> at: <a
href="http://www.cuttherope.ie/">www.cuttherope.ie</a>.</p><p>We think that the HTML5 version makes the web more fun and it demonstrates the advances in standards support made in the latest version of Internet Explorer. With that in mind, we want to share some of the cool “behind the scenes” technical details used on this project to help you build your own HTML5 sites and ultimately get ready for the <a
href="http://msdn.microsoft.com/en-us/windows">Windows 8 Store</a>!<div>  <script type='text/javascript'>GA_googleFillSlot("InArticle_728x90_1");</script> </div></p><p><img
class="alignnone size-full wp-image-51216" title="figure1" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/figure11.png" alt="Cut the Rope in IE9" width="220" height="220" /></p><p><em>Cut the Rope running in IE9 as an HTML5 application, ported from the original iOS source code.</em></p><p><img
class="alignnone size-full wp-image-51218" title="figure2" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/figure21.png" alt="special levels" width="220" height="171" /><br
/> <em> A screenshot of one of the specially designed levels that are uniquely available in this version.</em></p><p><strong>Objective-C to JavaScript</strong></p><p>In bringing <strong>Cut the Rope</strong> to a new platform, we wanted to ensure we preserved the unique physics, motion, and personality of the experience. So early on we decided to approach this game as a “port” from the native iOS version (rather than a rewrite). We kicked off the project with an extensive investigation of the original Objective-C codebase. Turns out it’s a big and complex game. The native iOS version consists of about 15,000 lines of code (excluding libraries)! The most complex parts of the codebase are the physics, animation, and drawing engines. They’re complex on their own, but made even more so by the fact that all three are tightly connected and highly optimized.</p><p>It was a daunting task: get this code into a browser while maintaining the unique personality and incredible quality that gamers are accustomed to. To accomplish this, we bet on JavaScript.</p><p>In the past, JavaScript had a reputation of being a slow language. Frankly, that reputation was initially valid. Older JavaScript engines were designed for simple “scripting” kinds of tasks (hence the name). Today, however, JavaScript engines have been highly optimized. With features like just-in-time compilation, JavaScript now can execute at near native speeds.</p><p>Beyond that, we know that coding for JavaScript is different from &#8211; and requires a different kind of mindset than &#8211; coding in a compiled language. As we ported the game from Objective-C, we knew we would need to embrace the task of making these sorts of changes and optimizations.</p><p>One obvious example was the lack of <em>structs</em> in JavaScript. Structs are lightweight aggregations of related properties. It’s easy to use a JavaScript object to hold a set of properties, but there are important differences between that approach and a proper struct. The first difference is that structs get copied whenever they’re assigned to a variable or passed to a function. So, a function written in a compiled language like Objective-C can modify a struct passed as a parameter without affecting the value in the caller. Even within a function, assignment of a struct to a different variable will copy the values. JavaScript objects, on the other hand, are passed by reference. So when a function modifies an object parameter, the changes will be visible to the caller.</p><p>An easy way to mimic the nature of structs is to create copies of JavaScript objects for assignment or parameter passing. In native languages there is typically very little overhead to using structs. Creating an object in JavaScript is much more expensive, so we had to be very careful to minimize the number of allocations. Particularly on assignments, whenever possible we tried to copy individual properties rather than creating entirely new object instances.</p><p>Another example is the object oriented nature of the Objective-C codebase. In lieu of traditional object-based inheritance, JavaScript offers prototypical inheritance, inheritance based on the Prototype property. This is a highly simplified form of object inheritance that really isn’t compatible with a traditional object oriented language like Objective-C. Fortunately, there are a variety of class libraries that can help you write object-oriented programming (OOP) style code for JavaScript; we made use of <a
href="http://ejohn.org/blog/simple-javascript-inheritance/">a very simple one</a> that was written by John Ressig (of jQuery fame). (Note that ECMAScript5, the specification for the newest version of JavaScript, also includes some support for classes but we opted not to use it in this port due to our lack of familiarity with that version of the language coupled with our aggressive development schedule).</p><p>In addition to porting from Objective-C to JavaScript, we also needed to port our graphics code from OpenGL to the HTML5 Canvas API. Overall, this went really smoothly. Canvas is an amazingly fast rendering surface, especially in a browser where that API is hardware accelerated (like Internet Explorer 9).</p><p><img
class="alignnone size-full wp-image-51219" title="figure3" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/figure31.png" alt="aliased lines" width="220" height="220" /></p><p><em>An example of drawing the ropes with aliased lines using the canvas API.</em></p><p>Surprisingly, we encountered a few areas where the Canvas provides more functionality than does the version of OpenGL ES that was used by the mobile version of Cut the Rope. One example is drawing <a
href="http://en.wikipedia.org/wiki/Spatial_anti-aliasing">anti-alias lines</a>. Drawing anti-aliased lines in OpenGL requires tessellating a line into a triangle strip and fading the opacity of the end caps to complete transparency. The HTML5 canvas automatically handles anti-aliasing for lines drawn with its line API. This meant we actually needed to remove code from the OpenGL version. Unwinding the array of triangle vertices in the OpenGL code also gave us much better performance over trying to natively copy the triangle strip method of drawing lines.</p><p>In the end, we have nearly 15,000 lines of code executing in the browser (it’s been minified so if you view the source code in your browser, it will be many lines fewer than that). Anticipating the complexity associated with that much code, Denis Morozov (the Director of Development at ZeptoLab) asked a fair question early on: will HTML5 give us the speed and performance that we need for this game?</p><p>To answer that, we created an early “performance” milestone, one where we focused on getting a minimal version of the most intense parts of the game running. Namely, we wanted to see what the ropes looked like and whether we could handle the complex physics engine in the browser.</p><p><strong>Performance</strong></p><p>Three weeks into the project, we finally had the basics of the physics and drawing engines in place with a simple timer to bootstrap the animation. We could now render a couple of ropes, a star, and an Om Nom sprite into the game scene. Progress! By week four, we had included some basic mouse interaction and with that we could actually play the game! We were testing performance along the way, but we wanted to let the team at ZeptoLab give us their feedback.</p><p>When we shared the code with ZeptoLab, they were pleasantly surprised by the performance (particularly the speed and smoothness from the game) that we were seeing in modern browsers. To be honest, we had been holding our breath just a little. We expected JavaScript to be fast but the physics calculations were intense and had to happen in real-time. This is a great example of where common preconceptions about the “slowness” of JavaScript turn out to be wrong. The latest generation of JavaScript engines is incredibly fast.</p><p>In this case, we were previewing the game in Internet Explorer 9. When you load the game, Internet Explorer 9’s Chakra JavaScript engine pre-compiles the code on a background thread—just as a compiler would compile a language like Objective-C or C++. It then, in real time, sends the compiled code (byte-code) to the game thread for execution. The result is near-native execution speeds. Amazingly, this is something that you just get for free from the JavaScript engine—we didn’t have to do anything special in the code.</p><p><img
class="alignnone size-full wp-image-51220" title="figure4" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/figure41.png" alt="framerate test results" width="220" height="220" /></p><p><em>Framerate test results early in the project (note that framerates are capped at 60FPS)</em></p><p>Our bet on JavaScript was paying off, so we turned our attention to hardware and browsers. With Internet Explorer’s hardware-accelerated rendering stack and our experience with <a
href="http://windowsteamblog.com/ie/b/ie/archive/2011/06/03/behind-the-scenes-of-disney-tron-legacy-digital-book-site.aspx">Disney Tron</a> and other <a
href="http://www.beautyoftheweb.com/">HTML5 sites</a>, we didn’t have any concerns about its ability to run the game perfectly on our test machines. We were easily hitting our capped goal of 60 FPS (frames per second). We wanted to be sure, however, that the game ran well on other hardware with other browsers. <a
href="http://www.cuttherope.ie/dev/notes-framerates.jpg">Here’s what we saw</a> after some preliminary testing.</p><p>Based on those numbers, we set 30 FPS as our minimum bar. We decided that when the browser goes below that threshold, we would notify the user. They could still play the game, but we’d inform them that it could feel a little bit sluggish. This ensures that we support the huge diversity of hardware and software that’s out there and provide the best experience we can to all of the game’s visitors.</p><p>Two things we want to point out. One, the current version of the game works best on desktop PCs and Macs with a mouse. We have not added the support for touch based input yet, but this is something we’re considering for future versions.</p><p>Second, the current version of Chrome (version 16) has <a
href="http://code.google.com/p/chromium/issues/detail?id=107933">known issues related to media playback</a> that make sound unpredictable in Cut the Rope. We researched workarounds and have attempted to re-encode the media in multiple formats (including WebM), but haven&#8217;t found a format or MIME configuration or anything else that will reliably fix the problem. These appear to be browser bugs and known issues. More importantly, the game continues to be playable and enjoyable in spite of the intermittent audio. In light of that, while we can say Internet Explorer 9 users get a great plug-in free experience, Chrome and some Firefox users could have run into an audio problem but will notice we fall back to a flash plugin to ensure that sound effects and music will work.</p><p><strong>Tools</strong></p><p>A great thing about HTML5 is that you don’t need to learn a new language to unlock the power of this new technology. If you know and understand JavaScript, you already have access to all that a modern browser can do. You could even create your own game like this!</p><p><strong>Code Editor and Development Environment</strong></p><p><img
class="alignnone size-full wp-image-51221" title="figure5" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/figure51.png" alt="VWD 2010 Express" width="220" height="161" /></p><p><em>Visual Web Developer 2010 Express is a free download and a great editor for even experienced web developers.</em></p><p><img
class="alignnone size-full wp-image-51222" title="figure6" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/figure61.png" alt="profiler screenshot" width="220" height="260" /></p><p><em>A screenshot from the profiler that shows the disproportionate amount of time being spent in Calc2PointBezier, a function that&#8217;s used to caculate the positions of the rope segments.</em></p><p>There are some great free tools that make working with JavaScript and HTML5 easy. Much of our development was done in Visual Web Developer 2010 (<a
href="http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-web-developer-express">the &#8220;express&#8221; version is available for free here</a>). This is a really robust web editor with autocompletion for JavaScript and CSS. It’s great that the express version is free! We did most of our testing in Internet Explorer 9 on Windows 7 and from time to time we would also test on Firefox, Chrome, Safari, and in Internet Explorer 10 developer preview. In general, all major browsers have a very consistent implementation of the HTML5 features we used and, in most cases, anything we tested in Internet Explorer 9 “just worked” everywhere else.</p><p><strong>Check out our Resource Loader!</strong></p><p>Cut the Rope has unique and very detailed visual styling &#8211; lots of media in the form of images, sounds and video &#8211; which comes at a small cost. The result is that the whole game is much bigger than an average website. Combined, it’s around 6 MB (compared to 200-300K for a typical site). That much media can take a little while to download and we can&#8217;t start the game until we know everything is there. A traditional web page is pretty forgiving if you&#8217;re missing an image or two but the HTML5 canvas API (drawImage) will fail if the image isn&#8217;t available.</p><p>To tackle this challenge, we wanted to create a resource loader that downloads all of the content we need for the page and gives us good feedback as things are downloaded. This bit of code does a bunch of smart things:</p><p>1. It deals with the peculiarities of how different browsers handle downloads and how they inform you of their progress.</p><p>2. It lets you make smart decisions about the order in which things are downloaded (you might want to start big files first, for example, or maybe download all of the menu images before you get the game images).</p><p>3. Finally, it gives you smart events as things arrive so that you can show the user progress or even start part of the game when the first group is completed.</p><p>Building these types of libraries is tricky to do well. Since we’re really pleased with how this all came together, we wanted to share the code for our resource loader with you. The result is PxLoader, a javascript Resource Loader library that you can user to make preloaders for HTML5 applications, games and sites. It&#8217;s open source and free. You can grab it from the top of the page, or just click <a
href="http://thinkpixellab.com/pxloader">here</a>.</p><p><strong>Performance Tools in Internet Explorer</strong></p><p>Another indispensable tool in the development process was the JavaScript Profiler in Internet Explorer 9. Profiling lets you discover hot spots and bottlenecks in your code. At one point in our first performance related milestone, we nearly called it quits when we discovered that on some machines we were stuck at 20 or 30 FPS.</p><p>We did some initial code reviews, but nothing was jumping out. We loaded the game with the profiler and immediately saw that we were spending a lot of time inside the satisfyConstraints() function. That function calculates some of the math related to the physics of the ropes. The Objective-C implementation which we had ported was written recursively, passing a new object into each successively deeper call.</p><p>With some guidance from Microsoft, we decided to replace the recursive function with an “unpacked” iterative version of the same code. The results were amazing. We saw a 10x improvement in every browser! Frankly, we would have never found that without the profiling tools in Internet Explorer 9.</p><p><strong>What’s next?</strong></p><p>At BUILD in September, Microsoft showed a developer preview of Windows 8. With this announcement, the HTML5 story got more interesting because Metro style applications can be created using a variety of developer toolsets, including HTML5. This means that web developers can take code that was written for the web and easily and seamlessly port it to Windows 8. The investment in immersive experiences online now can pay off in real profits later with the Windows Store.</p><p>In fact, with very little extra work, we were able to port this HTML5 experience to a Windows 8 Metro style app. Read about <strong>Cut the Rope</strong> and its integration with the Windows Store in <a
href="http://blogs.msdn.com/b/windowsstore/archive/2011/12/06/announcing-the-new-windows-store.aspx">this blog post</a>.</p><p>We are excited to see what developers can build today with HTML5. You can download Internet Explorer 9 and find other beautiful sites at <a
href="http://www.beautyoftheweb.com/">www.beautyoftheweb.com</a>, or download the Developer Preview of Windows 8 at <a
href="http://dev.windows.com/">dev.windows.com</a>.</p><div
style="text-align:center;padding-bottom:50px;"><div
style="float:left;padding-left:30px;"> <script>GA_googleFillSlot("Edit_300x100_C");</script> </div><div
style="float:right;padding-right:30px;"> <script>GA_googleFillSlot("Edit_300x100_D");</script> </div></div><div
style="clear:both"></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/bringing-cut-the-rope-to-life-in-an-html5-browser/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>How to Create Your Own Random Number Generator in PHP</title><link>http://www.sitepoint.com/php-random-number-generator/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=php-random-number-generator</link> <comments>http://www.sitepoint.com/php-random-number-generator/#comments</comments> <pubDate>Wed, 08 Feb 2012 15:50:17 +0000</pubDate> <dc:creator>Craig Buckler</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[PHP & MySQL Tutorials]]></category> <category><![CDATA[Technology]]></category> <category><![CDATA[random]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=50865</guid> <description><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/631-psuedo-random-php-50x50.png" class="attachment-thumbnail wp-post-image" alt="631-psuedo-random-php" title="631-psuedo-random-php" />Craig explains how you can write your own random number generator in PHP - and why you'd want to do that given that PHP has its own random generation functions.]]></description> <content:encoded><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/631-psuedo-random-php-50x50.png" class="attachment-thumbnail wp-post-image" alt="631-psuedo-random-php" title="631-psuedo-random-php" /><p></p><p>Computers cannot generate random numbers. A machine which works in ones and zeros is unable to magically invent its own stream of random data. However, computers can implement mathematical algorithms which produce pseudo-random numbers. They look like random numbers. They feel like random distributions. But they&#8217;re fake; the same sequence of digits is generated if you run the algorithm twice.</p><h2>Planting Random Seeds</h2><p>To increase the apparent randomness, most algorithms can be passed a seed &#8212; an initialization number for the random sequence. Passing the same seed twice will still generate the same set of random numbers but you can set the seed based on external input factors. The easiest option is the current time but it can be anything; the last keypress, a mouse movement, the temperature, the number of hours wasted on YouTube, or any other factor.</p><h2>Random PHP Functions</h2><p>PHP offers a number of random number functions. The main ones are:</p><ol><li><p><a
href="http://php.net/manual/en/function.rand.php">rand()</a> and the more efficient <a
href="http://www.php.net/manual/en/function.mt-rand.php">mt_rand()</a> function. Both return a random number between zero and <a
href="http://www.php.net/manual/en/function.getrandmax.php">getrandmax()</a>/<a
href="http://www.php.net/manual/en/function.mt-getrandmax.php">mt_getrandmax()</a>. Alternatively, you can pass minimum and maximum parameters:<div>  <script type='text/javascript'>GA_googleFillSlot("InArticle_728x90_1");</script> </div></p><pre><code>
// random number between 0 and 10 (inclusive)
echo mt_rand(0, 10);
</code></pre></li><li><p><a
href="http://www.php.net/manual/en/function.srand.php">srand($seed)</a> and <a
href="http://www.php.net/manual/en/function.mt-srand.php">mt_srand($seed)</a> to set a random number seed. This has been done automatically since PHP 4.2.0.</p></li></ol><h2>PHP is Too Random!</h2><p>There are instances when creating a repeatable list of pseudo-random numbers is useful. It&#8217;s often used for security or verification purposes, e.g. encrypting a password before it&#8217;s transmitted or generating a hash code for a set of data. Unfortunately, PHP can be a little <em>too</em> random. A generated sequence will depend on your hosting platform and version of PHP. In other words, you can&#8217;t guarantee the same &#8216;random&#8217; sequence will be generated twice on two different machines even if the same seed is used.</p><h2>Rolling Your Own Random Class</h2><p>Fortunately, we can write our own random number generator. You&#8217;ll find many algorithms on the web, but this is one of the shortest and fastest. First, we initialize our class and a random seed variable:</p><pre><code>
class Random {
	// random seed
	private static $RSeed = 0;
</code></pre><p>Next we have a seed() function for setting a new seed value. For the algorithm to work correctly, the seed should always be a positive number greater than zero but not large enough to cause mathematical overflows. The seed function takes any value but converts it to a number between 1 and 9,999,999:</p><pre><code>
	// set seed
	public static function seed($s = 0) {
		self::$RSeed = abs(intval($s)) % 9999999 + 1;
		self::num();
	}
</code></pre><p>Finally, we have our num() function for generating a random number between $min and $max. If no seed has been set it&#8217;s initialized with PHP&#8217;s own random number generator:</p><pre><code>
	// generate random number
	public static function num($min = 0, $max = 9999999) {
		if (self::$RSeed == 0) self::seed(mt_rand());
		self::$RSeed = (self::$RSeed * 125) % 2796203;
		return self::$RSeed % ($max - $min + 1) + $min;
	}
}
</code></pre><p>We can now set a seed and output a sequence of numbers:</p><pre><code>
// set seed
Random::seed(42);
// echo 10 numbers between 1 and 100
for ($i = 0; $i &lt; 10; $i++) {
	echo Random::num(1, 100) . '&lt;br /&gt;';
}
</code></pre><p>If you&#8217;ve copied this code exactly, you should see the following values no matter what OS or version of PHP you&#8217;re running:</p><pre>
76
86
14
79
73
2
87
43
62
7
</pre><p>Admittedly, repeatable <em>&#8220;random&#8221;</em> numbers isn&#8217;t something you&#8217;ll need every day &#8212; you&#8217;re more likely to require something closer to real randomness and PHP&#8217;s functions will serve you better. But there may be occasions when you find this useful.</p><div
style="text-align:center;padding-bottom:50px;"><div
style="float:left;padding-left:30px;"> <script>GA_googleFillSlot("Edit_300x100_C");</script> </div><div
style="float:right;padding-right:30px;"> <script>GA_googleFillSlot("Edit_300x100_D");</script> </div></div><div
style="clear:both"></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/php-random-number-generator/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Microsoft HTML5 Web Camp Videos Now Online</title><link>http://www.sitepoint.com/microsoft-html5-web-camp-videos-now-online/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=microsoft-html5-web-camp-videos-now-online</link> <comments>http://www.sitepoint.com/microsoft-html5-web-camp-videos-now-online/#comments</comments> <pubDate>Wed, 08 Feb 2012 10:47:17 +0000</pubDate> <dc:creator>Ricky Onsman</dc:creator> <category><![CDATA[Client Side Coding]]></category> <category><![CDATA[HTML & CSS]]></category> <category><![CDATA[HTML5]]></category> <category><![CDATA[Tutorials]]></category> <category><![CDATA[Web Tech]]></category> <category><![CDATA[HTML5 Dev Center]]></category> <category><![CDATA[microsoft]]></category> <category><![CDATA[Webcamp]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=51188</guid> <description><![CDATA[<img
width="50" height="34" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/html5webcamp-50x34.png" class="attachment-thumbnail wp-post-image" alt="html5webcamp" title="html5webcamp" />If you missed November's live streaming of the <b>Microsoft HTML5 Web Camp</b> held in Mountain View, California, we can now provide recorded video of the sessions.
]]></description> <content:encoded><![CDATA[<img
width="50" height="34" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/html5webcamp-50x34.png" class="attachment-thumbnail wp-post-image" alt="html5webcamp" title="html5webcamp" /><p></p><p>Back in November, we were able to provide live streaming video for the Microsoft HTML5 Web Camp held in Mountain View, California.</p><p>For those who missed the live action &#8211; and those who want to revisit some of the sessions &#8211; we can now provide recorded video of the event, right here.</p><p>There are four videos, covering different sections of the camp.</p><p>The first video covers the morning session: <strong>Welcome</strong> by Joe Shirey; <strong>Introduction to HTML5</strong> by Doris Chen, and <strong>Introduction to CSS3</strong> by William Leong.</p><p><iframe
style="height: 363px; width: 717px;" src="http://channel9.msdn.com/Events/HTML5-Web-Camp/HTML5-Web-Camp-Silicon-Valley/HTML5-AM-Sessions/player?w=717&amp;h=363" frameborder="0" scrolling="no"></iframe></p><p>The second video features Doris Chen&#8217;s <strong>Overview of HTML5 Graphics: Canvas &amp; SVG</strong>.</p><p><iframe
style="height: 363px; width: 717px;" src="http://channel9.msdn.com/Events/HTML5-Web-Camp/HTML5-Web-Camp-Silicon-Valley/Overview-of-HTML5-Graphics-with-Canvas-SVG/player?w=717&amp;h=363" frameborder="0" scrolling="no" width="320" height="240"></iframe></p><p>The third video is <strong>Adding Video, and Sound with HTML5</strong> and <strong>Practical HTML5: Using It Today</strong>, both with Doris Chen.</p><p><iframe
style="height: 363px; width: 717px;" src="http://channel9.msdn.com/Events/HTML5-Web-Camp/HTML5-Web-Camp-Silicon-Valley/HTML5-Web-Camp-PM-Sessions-Adding-Audio-and-Video-Practical-HTML5/player?w=717&amp;h=363" frameborder="0" scrolling="no" width="320" height="240"></iframe><div>  <script type='text/javascript'>GA_googleFillSlot("InArticle_728x90_1");</script> </div></p><p>The fourth video covers Doris Chen&#8217;s instructions for <strong>setting up the Lab</strong> and Alice Pang&#8217;s demonstration of <strong>WebMatrix</strong>.</p><p><iframe
style="height: 363px; width: 717px;" src="http://channel9.msdn.com/Events/HTML5-Web-Camp/HTML5-Web-Camp-Silicon-Valley/HTML5-Web-Camp-Lab-setup-Demo/player?w=717&amp;h=363" frameborder="0" scrolling="no" width="320" height="240"></iframe></p><p>You can also view these videos and download pdfs of slides used in the presentations at <a
href="http://channel9.msdn.com/Events/HTML5-Web-Camp/HTML5-Web-Camp-Silicon-Valley">http://channel9.msdn.com/Events/HTML5-Web-Camp/HTML5-Web-Camp-Silicon-Valley</a></p><div
style="text-align:center;padding-bottom:50px;"><div
style="float:left;padding-left:30px;"> <script>GA_googleFillSlot("Edit_300x100_C");</script> </div><div
style="float:right;padding-right:30px;"> <script>GA_googleFillSlot("Edit_300x100_D");</script> </div></div><div
style="clear:both"></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/microsoft-html5-web-camp-videos-now-online/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>3 Breakthrough Ways to Visualize HTML5 Audio</title><link>http://www.sitepoint.com/3-breakthrough-ways-to-visualize-html5-audio/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=3-breakthrough-ways-to-visualize-html5-audio</link> <comments>http://www.sitepoint.com/3-breakthrough-ways-to-visualize-html5-audio/#comments</comments> <pubDate>Tue, 07 Feb 2012 00:04:05 +0000</pubDate> <dc:creator>Konstantin Kichinsky</dc:creator> <category><![CDATA[Client Side Coding]]></category> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Web Tech]]></category> <category><![CDATA[HTML5 Audio]]></category> <category><![CDATA[HTML5 Dev Center]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=51098</guid> <description><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/feature2-50x50.png" class="attachment-thumbnail wp-post-image" alt="feature" title="feature" />Konstantin Kichinsky focuses on an interesting scenario that isn’t directly covered by the HTML5 standard, but is in high demand and visually impressive: audio visualization using HTML5 Audio.]]></description> <content:encoded><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/feature2-50x50.png" class="attachment-thumbnail wp-post-image" alt="feature" title="feature" /><p></p><p>Today, HTML5 is kind of like a TV series without any future seasons written yet.</p><p>It has some episodes already filmed, some raw material that needs to be edited, some shots that are in line for cool special effects, and many, many rough drafts. Yeah, I&#8217;m talking about the whole HTML5 story, not just the spec, but hopefully you get the idea.</p><p>I’m going to focus on one interesting scenario that isn’t directly covered by the HTML5 standard, but is in high demand and visually impressive. It’s audio visualization using HTML5 Audio <a
href="http://www.beautyoftheweb.com/firework">like this</a>:</p><p><img
class="alignnone size-full wp-image-51100" title="figure1" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/figure1.png" alt="figure 1" width="453" height="300" /></p><p>In my TV series analogy, audio visualization (specifically low-level API to access an audio stream) falls squarely between early drafts and ideas for future series.</p><h3><strong>What you can do with Audio … and what you can&#8217;t</strong></h3><p>The Audio element in HTML5, as you may already have guessed, doesn&#8217;t provide low-level API. It does allow you to manage the audio stream playback on a high level: play and pause, set and get current position on the timeline, know total duration, work with text tracks, and control volume level.<div>  <script type='text/javascript'>GA_googleFillSlot("InArticle_728x90_1");</script> </div></p><p>If you try to do anything more complex than playing a single music file with Audio—like synchronizing audio samples—you’ll realize it’s not as easy as you’d like it to be.</p><p>There are also limitations around other audio tasks that you might want to implement on your site:</p><ul><li>Support for multiple file <a
href="http://msdn.microsoft.com/en-us/library/gg589524%28v=VS.85%29.aspx">formats or codecs</a> like MP3 and H.264</li><li>Browser features for <a
href="http://blogs.msdn.com/b/ie/archive/2011/05/13/unlocking-the-power-of-html5-lt-audio-gt.aspx">controlling music players</a></li><li><a>Browser pre-processing</a> and network testing</li></ul><p>As you can see, it depends not only on the spec itself, but also on real implementation in real browsers.</p><p><strong>Future</strong><strong> standards </strong><strong>for audio … maybe</strong><strong></strong></p><p><img
class="alignnone size-full wp-image-51101" title="figure2" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/figure2.png" alt="figure 2" width="256" height="256" /></p><p>There is an initiative happening to provide the low-level API for audio stream by the <a
href="http://www.w3.org/2011/audio/">Audio Working Group at W3C</a>.</p><blockquote><p><em>“The audio API will provide methods to read audio samples, write audio data, create sounds, and perform client-side audio processing and synthesis with minimal latency. It will also add programmatic access to the PCM audio stream for low-level manipulation directly in script.”</em></p></blockquote><p>So, maybe someday in the future, we’ll see a common, standards-based solution for audio stream manipulations.</p><p>In the meantime, let’s come back to the real world and dive into what we can do with HTML5 today.</p><h3><strong>Practical approach: what can I do today?</strong></h3><p>First of all, what exactly do you need to build a visualization? You need some data that is time-aligned with the audio playback. It could be textual information like lyrics, data representing volume levels, or any other data you want to play with.</p><p>Where can you get data? The practical way is <a
href="http://blogs.msdn.com/b/ie/archive/2011/05/13/unlocking-the-power-of-html5-lt-audio-gt.aspx">preprocessing</a>. Yeah! So simple and trivial …</p><p>Basically, you’ll need to do some homework if you want to visualize audio. Analyze your audio stream first, and then you’ll be able to generate a visualization synchronized with the audio playing in the background.</p><p>For example, if you want to extract semantically important data (like lyrics for a song), preprocessing is the only possible solution (unless you have enough skilled AI to understand words and sentences in a song).</p><p>Usually, it’s a tedious, manual task. You sit down, turn on your audio player, start playing the song, remember a line, pause, write it down, look at the timer, write down current time … and do it again and again. Sometimes, you can just pull it from the Internet somewhere.</p><p>The fact is, preprocessing is just plain efficient. Using this approach saves computational resources and consequently reduces the load on the client side. That means that you should compute (or write) your data for audio visualization only once, then just use this data to make your magic happen anytime you want.</p><p>Now let’s see how it works in real life…</p><h3>Dealing with real-world examples</h3><p>To familiarize yourself with all the great solutions I’ll address in a moment, you can use the developer tools in your favorite browser.  Internet Explorer provides great <a
href="http://msdn.microsoft.com/en-us/library/gg589512%28v=VS.85%29.aspx">devtools</a> for this purpose &#8211; just press F12.  You can use the Scripts panel to look into JavaScript code, debug it, set breakpoints, or run your own code in the console.</p><p><img
class="alignnone size-full wp-image-51102" title="figure3" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/figure3.png" alt="figure 3" width="500" height="359" /></p><p>Sometimes you will need to deal with compacted (or minified) code. In that case, just press “Format JavaScript” to make it more readable.</p><p><img
class="alignnone size-full wp-image-51103" title="figure4" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/figure4.png" alt="figure 4" width="500" height="357" /></p><h3>Example #1: Chell in the Rain</h3><p><img
class="alignnone size-full wp-image-51104" title="figure5" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/figure5.png" alt="figure 5" width="500" height="386" /></p><p><a
title="Chell in the Rain" href="http://sorrowind.net/vilify/">Chell in the Rain</a> is a stunning audio-textual visualization of the song <a
title="Exile Vilify" href="http://itunes.apple.com/us/album/exile-vilify-from-game-portal/id432601217">Exile Vilify</a> created by <a
href="http://twitter.com/#%21/matt_merkle">Matthew Merkle</a>. You’ll see the lyrics for the song appear in perfect sync with the audio stream.</p><p><strong>What’s inside</strong></p><ul><li>jQuery + <a
title="Sizzle" href="http://sizzlejs.com/">Sizzle.js</a> (building jQuery)</li><li><a
title="jPlayer" href="http://www.jplayer.org/">jPlayer</a> (a library to play Audio and Video)</li><li>And some code that we’re interested in ;)</li></ul><p><strong>How it works</strong></p><p>The song is split into a few fragments or timeframes (or timings) pointing to the beginning of a phrase or some animation. All the timings are stored in an array:</p><pre>var timings = newArray();
timings[0] = 11.5;
timings[1] = 17;
timings[2] = 24;
timings[3] = 29;
timings[4] = 35.5;</pre><p>In parallel, there is an array of lyrics:</p><pre>var lyrics = newArray();
lyrics[0] = 'Exile';
lyrics[1] = 'It takes your mind... again';
lyrics[2] = "You've got sucker's luck";
lyrics[3] ='Have you given up?';</pre><p>Now the current time on the playback can be linked with the timings array and fire a corresponding event trigger to jump for the next phrase:</p><pre>if(event.jPlayer.status.currentTime &gt;= timings[currentTrigger] &amp;&amp; nolyrics != true) {
    fireTrigger(currentTrigger);
    currentTrigger++;
}</pre><p>Next, the fired trigger makes some animations using jQuery:</p><pre>function fireTrigger(trigger) {
    switch (trigger) {
        case 0:
            $('#lyrics1 p').addClass('vilify').html(lyrics[0]).fadeIn(1500);
            break;
        case 1:
            $('#lyrics2 p').html(lyrics[1]).fadeIn(1000).delay(5000).fadeOut(1000);
            $('#lyrics1 p').delay(6000).fadeOut(1000);
            break;
        case 2:
            $('#lyrics1 p').fadeIn(1000);
            break;
        case 3:
            $('#lyrics2 p').fadeIn(1000).delay(4000).fadeOut(1000);
            $('#lyrics1 p').delay(5000).fadeOut(1000);
            break;
        case 4:
           $('#lyrics1 p').removeClass('vilify').html(lyrics[2]).fadeIn(1000);
           break;
        case 5:
           $('#lyrics2 p').html(lyrics[3]).fadeIn(1000).delay(3000).fadeOut(1000);
           $('#lyrics1 p').delay(4000).fadeOut(1000);
           break;
...</pre><p>It is quite simple and very effective.</p><p>Notice how easily you can mix audio stream playback and features of HTML, CSS and JavaScript.</p><h3>Example #2: Extracting audio data</h3><p><img
class="alignnone size-full wp-image-51105" title="figure6" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/figure6.png" alt="figure 6" width="500" height="325" /></p><p>In his blog post <a
title="Music Visualizer in HTML5 / JS with Source Code" href="http://gskinner.com/blog/archives/2011/03/music-visualizer-in-html5-js-with-source-code.html">Music Visualizer in HTML5 / JS with Source Code</a>, Grant shares his experience with audio visualization using HTML5.</p><p>Since HTML5 Audio doesn’t provide any API to extract low-level data from audio files, Grand wrote a small <a
href="http://gskinner.com/blog/assets/VolumeData.zip">AIR application</a> (with samples) to help us extract the data on volume levels from an MP3 file, then store it in a text file or an image.</p><p>Zoomed in, the volume levels data looks like this:</p><p><img
class="alignnone size-full wp-image-51106" title="figure7" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/figure7.png" alt="figure 7" width="500" height="289" /></p><p>Now, with this image, we can easily extract all the data we need using HTML5 Canvas. And it is much easier for text files—I&#8217;m not showing it as it makes no sense to read it yourself as all the data is compressed.</p><p>To work with this type of preprocessed data, Grant also wrote a small JS-library (VolumeData.js, part of the .zip I downloaded above).</p><p>To visualize something, you need to load the data first:</p><pre>loadMusic("music.jpg");</pre><p>The function loadMusic just loads the image:</p><pre>function loadMusic(dataImageURL) {
    image = new Image();
    image.src = dataImageURL;
    playing = false;
    Ticker.addListener(window);
}</pre><p>Now you should create a new VolumeData object:</p><pre>volumeData = new VolumeData(image);</pre><p>And then on each time update, you can do everything you want using average volume data for current time or separate data for each of the channels (left and right):</p><pre>var t = audio.currentTime;
var vol = volumeData.getVolume(t);
var avgVol = volumeData.getAverageVolume(t-0.1,t);
var volDelta = volumeData.getVolume(t-0.05);
volDelta.left = vol.left-volDelta.left;
volDelta.right = vol.right-volDelta.right;</pre><p>All visual effects are done based on this data. For visualization, Grant is using the <a
title="EaselJS" href="http://easeljs.com/">EaselJS</a> library. Here are some samples: <a
href="http://easeljs.com/demos/MusicVisualizer/index.html">Star Field</a> and <a
href="http://easeljs.com/demos/MusicVisualizer/index2.html">Atomic</a>.</p><p>Now you have all the tools you need to make cool audio visualizations.</p><p>To sum up: Use preprocessing to make your solution more efficient. Try combining audio playback with textual data, animations, and graphic effects based on the volume levels data to make compelling user experiences. Make it look like it’s magic!</p><h3>Additional resources and more information:</h3><p><a
title="Unlocking the power of HTML5 <audio>&#8221; href=&#8221;http://blogs.msdn.com/b/ie/archive/2011/05/13/unlocking-the-power-of-html5-lt-audio-gt.aspx&#8221;>Unlocking the power of HTML5 Audio</a>, on the IE team blog, describes the basics steps and best practices for working with audio in HTML.</p><h3>Samples in this article:</h3><ul><li><a
href="http://www.beautyoftheweb.com/firework">Mike Tompkins Firework</a></li><li><a
title="Chell in the Rain" href="http://sorrowind.net/vilify/">Chell in the Rain</a></li></ul><h3>Downloads:</h3><ul><li>Grant Skinner’s <a
href="http://gskinner.com/blog/assets/VolumeData.zip">AIR application</a>(.zip)</li><li><a
title="Sizzle" href="http://sizzlejs.com/">Sizzle.js</a></li><li><a
title="jPlayer" href="http://www.jplayer.org/">jPlayer</a> Library</li><li><a
href="http://easeljs.com/">Easel JS Library</a></li></ul><div
style="text-align:center;padding-bottom:50px;"><div
style="float:left;padding-left:30px;"> <script>GA_googleFillSlot("Edit_300x100_C");</script> </div><div
style="float:right;padding-right:30px;"> <script>GA_googleFillSlot("Edit_300x100_D");</script> </div></div><div
style="clear:both"></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/3-breakthrough-ways-to-visualize-html5-audio/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Build Awesome Apps with CSS3 Animations</title><link>http://www.sitepoint.com/build-awesome-apps-with-css3-animations/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=build-awesome-apps-with-css3-animations</link> <comments>http://www.sitepoint.com/build-awesome-apps-with-css3-animations/#comments</comments> <pubDate>Fri, 03 Feb 2012 13:25:28 +0000</pubDate> <dc:creator>David Rousset</dc:creator> <category><![CDATA[CSS Tutorials]]></category> <category><![CDATA[HTML & CSS]]></category> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript & CSS]]></category> <category><![CDATA[Web Tech]]></category> <category><![CDATA[animation]]></category> <category><![CDATA[HTML5 Dev Center]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=51035</guid> <description><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/feature1-50x50.png" class="attachment-thumbnail wp-post-image" alt="feature" title="feature" />Today’s HTML5 applications can provide awesome experiences thanks partly  to CSS3 specifications like Animations. David Rousset walks you (and a Star Wars AT-AT) through the motions.]]></description> <content:encoded><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/feature1-50x50.png" class="attachment-thumbnail wp-post-image" alt="feature" title="feature" /><p></p><p>Today’s HTML5 applications can provide awesome experiences thanks to the new CSS3 specifications. One of them is <strong>CSS3 Animations</strong>. It can help you building rich animations on HTML elements. This can provide interesting feedbacks to the users and enables fast &amp; fluid UIs. As those new animations are most of the time hardware accelerated by the GPU, they definitely raise the quality bar of the new generation of HTML5 applications.</p><p>According to the “CSS Animation Module Level 3” specification on the <a
href="http://www.w3.org/TR/css3-animations/">W3C site</a>, CSS3 Animations <em>introduces defined animations, which specify the values that CSS properties will take over a given time interval. This specification is an extension to CSS Transitions</em>.</p><p>As CSS3 Animation is an <strong>extension to CSS3 Transitions</strong>, you should first read the article of my colleague David Catuhe on Transitions here: <a
href="http://blogs.msdn.com/b/eternalcoding/archive/2011/11/01/css3-transitions.aspx">Introduction to CSS3 Transitions</a>.</p><p>We’ll see in this article an interesting demo highlighting the potential of CSS3 animations, how to build simple animations &amp; how to handle fallback in JavaScript:</p><ol
start="1"><li><a
href="http://blogs.msdn.com/b/davrous/archive/2011/12/06/introduction-to-css3-animations.aspx#intro">CSS3 Animations</a></li><li><a
href="http://blogs.msdn.com/b/davrous/archive/2011/12/06/introduction-to-css3-animations.aspx#support">Browsers Support</a></li><li><a
href="http://blogs.msdn.com/b/davrous/archive/2011/12/06/introduction-to-css3-animations.aspx#fallback">CSS3 Animations JavaScript fallback library</a></li><li><a
href="http://blogs.msdn.com/b/davrous/archive/2011/12/06/introduction-to-css3-animations.aspx#conclusion">Conclusion</a></li></ol><p>Let’s first start by quickly demonstrating what CSS3 Animations are. Here is a sample animation of a Star Wars AT-AT which uses CSS3 Animations to animate parts of the transport (and which will fall back to JavaScript if your browser doesn’t support CSS3 Animations):<div>  <script type='text/javascript'>GA_googleFillSlot("InArticle_728x90_1");</script> </div></p><p><iframe
style="border-width: 0px; border-style: solid; border-color: #ffffff;" src="http://david.blob.core.windows.net/html5/css3atat/index.htm" scrolling="no" width="716" height="570"></iframe></p><p>You can test this sample also in a separate window here: <a
title="http://david.blob.core.windows.net/html5/css3atat/index.htm" href="http://david.blob.core.windows.net/html5/css3atat/index.htm">http://david.blob.core.windows.net/html5/css3atat/index.htm</a></p><p><strong><span
style="text-decoration: underline;">Note:</span></strong> this sample has been tested successfully with native animations under IE10 PP3/PP4, Chrome 15, Firefox 8 &amp; iPad 2 and with JS fallback under IE9 desktop &amp; mobile (Windows Phone). For an unknown reason, it behaves in weird way under Opera 11.50 but works fine with the 11.60. Moreover, our lovely blogging platform is most of the time forcing the IE9 rendering engine via a meta tag. To force it back to the IE10 standards mode, press the F12 key and change the value of “Document Mode” back to IE10. Otherwise, view the demo in a separate window.</p><p>This sample is based on the awesome work done by <a
href="http://twitter.com/acalzadilla">Anthony Calzadilla</a>. You can check other incredible demos on his website here: <a
href="http://www.anthonycalzadilla.com/">http://www.anthonycalzadilla.com</a> . I’m a huge fan of the <a
href="http://www.anthonycalzadilla.com/i-twitty-the-fool/">I twitty the fool</a> sample using SVG &amp; CSS3 Animation for instance.</p><h3>CSS3 Animations</h3><h4>Introduction</h4><p>Let’s first review on what you can play to build the animations. CSS3 Animations works basically on the same values as CSS3 Transition.</p><p>Here they are:</p><ul><li><strong>color</strong>: interpolated via red, green, blue and alpha components (treating each as a number, see below)</li><li><strong>length</strong>: interpolated as real numbers.</li><li><strong>percentage</strong>: interpolated as real numbers.</li><li><strong>integer</strong>: interpolated via discrete steps (whole numbers). The interpolation happens in real number space and is converted to an integer using floor().</li><li><strong>number</strong>: interpolated as real (floating point) numbers.</li><li><strong>transform list</strong>: see CSS Transforms specification: <a
href="http://www.w3.org/TR/css3-2d-transforms/">http://www.w3.org/TR/css3-2d-transforms/</a></li><li><strong>rectangle</strong>: interpolated via the x, y, width and height components (treating each as a number).</li><li><strong>visibility</strong>: interpolated via a discrete step. The interpolation happens in real number space between 0 and 1, where 1 is &#8220;visible&#8221; and all other values are &#8220;hidden&#8221;.</li><li><strong>shadow</strong>: interpolated via the color, x, y and blur components (treating them as color and numbers where appropriate). In the case where there are lists of shadows, the shorter list is padded at the end with shadows whose color is transparent and all lengths (x, y, blur) are 0.</li><li><strong>gradient</strong>: interpolated via the positions and colors of each stop. They must have the same type (radial or linear) and same number of stops in order to be animated.</li><li><strong>paint server</strong> (SVG): interpolation is only supported between: gradient to gradient and color to color. They then work as above.</li><li><strong>space-separated list of above</strong>: If the lists have the same number of items, each item in the list is interpolated using the rules above. Otherwise, no interpolation.</li><li><strong>a shorthand property</strong>: If all the parts of a shorthand can be animated, then interpolation is performed as if each property was individually specified.</li></ul><p>And the following properties must be supported for animations:</p><ul><li>background-color (<em>color</em>)</li><li>background-image (<em>only gradients</em>)</li><li>background-position (<em>percentage and length</em>)</li><li>border-bottom-color (<em>color</em>)</li><li>border-bottom-width (<em>length</em>)</li><li>border-color (<em>color</em>)</li><li>border-left-color (<em>color</em>)</li><li>border-left-width (<em>length</em>)</li><li>border-right-color (<em>color</em>)</li><li>border-right-width (<em>length</em>)</li><li>border-spacing (<em>length</em>)</li><li>border-top-color (<em>color</em>)</li><li>border-top-width (<em>length</em>)</li><li>border-width (<em>length</em>)</li><li>bottom (<em>length and percentage</em>)</li><li>color (<em>color</em>)</li><li>crop (<em>rectangle</em>)</li><li>font-size (<em>length and percentage</em>)</li><li>font-weight (<em>number</em>)</li><li>grid-* (<em>various</em>)</li><li>height (<em>length and percentage</em>)</li><li>left (<em>length and percentage</em>)</li><li>letter-spacing (<em>length</em>)</li><li>line-height (<em>number, length and percentage</em>)</li><li>margin-bottom (<em>length</em>)</li><li>margin-left (<em>length</em>)</li><li>margin-right (<em>length</em>)</li><li>margin-top (<em>length</em>)</li><li>max-height (<em>length and percentage</em>)</li><li>max-width (<em>length and percentage</em>)</li><li>min-height (<em>length and percentage</em>)</li><li>min-width (<em>length and percentage</em>)</li><li>opacity (<em>number</em>)</li><li>outline-color (<em>color</em>)</li><li>outline-offset (<em>integer</em>)</li><li>outline-width (<em>length</em>)</li><li>padding-bottom (<em>length</em>)</li><li>padding-left (<em>length</em>)</li><li>padding-right (<em>length</em>)</li><li>padding-top (<em>length</em>)</li><li>right (<em>length and percentage</em>)</li><li>text-indent (<em>length and percentage</em>)</li><li>text-shadow (<em>shadow</em>)</li><li>top (<em>length and percentage</em>)</li><li>vertical-align (<em>keywords, length and percentage</em>)</li><li>visibility (<em>visibility</em>)</li><li>width (<em>length and percentage</em>)</li><li>word-spacing (<em>length and percentage</em>)</li><li>z-index (<em>integer</em>)</li><li>zoom (<em>number</em>)</li></ul><h4>SVG</h4><p>The properties of SVG objects are animatable when they are defined as <strong>animatable:true</strong> in the SVG specification: <a
href="http://www.w3.org/TR/SVG/struct.html">http://www.w3.org/TR/SVG/struct.html</a>. But at the time where this article is written, I didn’t manage to combine CSS3 Animation directly on SVG elements in any of the latest browsers versions. Today’s samples on the web are then doing a little trick: they are embedding SVG resources into different DIV animated by CSS3 like the <a
href="http://www.anthonycalzadilla.com/i-twitty-the-fool/">I twitty the fool</a> sample.</p><h4>Declarations</h4><p>To declare an animation in a CSS file, here is the kind of generic code you’ll need to write:</p><pre>@keyframes name_of_the_animation {
  from {
    property_to_animate: initial_value;
  }
  50% {
    property_to_animate: intermediate_value;
  }
  to {
    property_to_animate: final_value;
  }
}</pre><p>Which could also be written like that:</p><pre>@keyframes name_of_the_animation {
  0% {
    property_to_animate: initial_value;
  }
  50% {
    property_to_animate: intermediate_value;
  }
  100% {
    property_to_animate: final_value;
  }
}</pre><p>This animation definition declares 3 steps 0, 50 &amp; 100%. You should at least set a <strong><em>from</em></strong> (or 0%) and a <strong><em>to</em></strong> (or 100%) steps to build a correct animation (minimum 2 steps thus). Once done, you may add as many keyframes as you’d like between 0 and 100% to handle precisely the various steps of your animations.</p><p>Once the definition is declared, you can affect it to an element using the classical CSS3 selectors and you’ll need also to configure the animation options. Here the kind of generic blocks you’ll see:</p><pre>#id_of_the_html_element {
    animation-name: name_of_the_animation;
    animation-duration: number_of_seconds s;
    animation-iteration-count: number | infinite;
}</pre><p>To better understand, let’s review a real sample. First of all, as the CSS3 Animations specification is still in a draft stage, you’ll need to use the appropriate vendor prefix. Let’s use IE10 as a sample with the –ms prefix then. Let’s now see how the head of our AT-AT is moving.</p><p>Here’s the animation declaration:</p><pre>@-ms-keyframes rotate-skull {
    0% {
        -ms-transform: rotate(0deg)
    }
    25% {
        -ms-transform: rotate(15deg)
    }
    50% {
        -ms-transform: rotate(-5deg)
    }
    55% {
        -ms-transform: rotate(0deg)
    }
    75% {
        -ms-transform: rotate(-10deg)
    }
    100% {
        -ms-transform: rotate(0deg)
    }
}</pre><p>We’ve got 6 steps (0, 25, 50, 55, 75 &amp; 100%) working on the CSS3 2D transform attributes by changing the value of the rotation.</p><p>The animation is then applied via this CSS rule:</p><pre>#skull
{
    -ms-animation-name: rotate-skull;
    -ms-animation-duration: 7s;
    -ms-animation-iteration-count: infinite;
}</pre><p>We’re targeting the <code>&lt;div&gt;</code> element having the “<code>id=<strong>skull</strong></code>” and we’re applying the animation named “<strong><code>rotate-skull</code></strong>” on it. The animation will have to be completed in <strong>7s</strong> and be played an <strong>infinite</strong> number of times.</p><p>Here is the living result if your browser supports CSS3 Animations:</p><p><iframe
style="border-bottom: #ffffff 0px solid; border-left: #ffffff 0px solid; border-top: #ffffff 0px solid; border-right: #ffffff 0px solid" height="200" src="http://david.blob.core.windows.net/html5/css3atat/AnimSkullATAT.htm" width="400" scrolling="no"></iframe></p><p>We could have written this rule in a shorter manner using the animation shorthand property:</p><pre>#skull {
    -ms-animation: rotate-skull 7s infinite;
}</pre><p>The animations will be triggered as soon as a matching rule is applied. You can then play or stop animations simply via <strong>JavaScript</strong> or via CSS3 to play with the <strong>classes affected to a tag</strong>.</p><h4>Non-linear animations</h4><p>The “animation-timing-function” property can be used if you want non-linear animations. You can even mix the type of timing functions during each keyframe.</p><p>Basically, CSS3 animations will use <a
href="http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B.C3.A9zier_curves">cubic bezier curve</a> to smooth the animation by computing different speed over its duration.</p><p>The following functions are supported:</p><ul><li><em>linear</em>: Constant speed</li><li><em>cubic-bezier</em>: Speed will be computed according to a cubic bezier curve define by two control points : P0 and P1 (so you will have to define 4 values here : P0x, P0y and P1x, P1y.</li><li><em>ease</em>: Speed will be computed with cubic-bezier(0.25, 0.1, 0.25, 1)</li><li><em>ease-in</em>: Speed will be computed with cubic-bezier(0.42, 0, 1, 1)</li><li><em>ease-inout</em>: Speed will be computed with cubic-bezier(0.42, 0, 0.58, 1)</li><li><em>ease-out</em>: Speed will be computed with cubic-bezier(0, 0, 0.58, 1)</li></ul><p>Here is a simulation tool written by <a
href="http://blogs.msdn.com/b/eternalcoding/archive/2011/11/01/css3-transitions.aspx">David Catuhe</a> that uses pure JavaScript to show the impact of each timing function:</p><p><iframe
style="border-bottom: #ffffff 0px solid; border-left: #ffffff 0px solid; border-top: #ffffff 0px solid; border-right: #ffffff 0px solid" height="650" src="http://www.catuhe.com/msdn/transitions/easingfunctions.htm" width="1000"></iframe></p><p><strong><span
style="text-decoration: underline;">Note:</span></strong> this tool uses in-line SVG supported by Firefox, Chrome, Opera 11.60 &amp; IE9/10. It won’t work properly under Opera 11.50 &amp; Safari on iPad thus.</p><p>This is an awesome tool using SVG. You can even play with your mouse on the custom function to edit the curve. If you’d like to know more about this tool, please again have a look to David’s article.</p><p>If your browser supports CSS3 animations, let’s now see a simple demo using <strong>easing functions to animate a canvas tag</strong> containing an animated sprite with CSS3.</p><p>Here is the CSS3 animations code that will be used in this demo:</p><pre>@-ms-keyframes demo {
    from {
    -ms-animation-timing-function: ease;
    -ms-transform: translateX(0px);
    }
    50% {
    -ms-animation-timing-function: ease-in;
    -ms-transform: translateX(300px);
    }
    to {
    -ms-animation-timing-function: ease-inout;
    -ms-transform: translateX(900px);
    }
}
&nbsp;
#testCanvas
{
    -ms-animation-delay: 0s;
    -ms-animation-duration: 6s;
    -ms-animation-iteration-count: infinite;
    -ms-animation-name: demo;
}</pre><p>As well as all the vendor prefixes variations to make sure it works also in Google Chrome &amp; Mozilla Firefox. And here’s the living output:</p><p><iframe
style="border-bottom: #ffffff 0px solid; border-left: #ffffff 0px solid; border-top: #ffffff 0px solid; border-right: #ffffff 0px solid" height="90" src="http://david.blob.core.windows.net/html5/css3animcanvas/sprites.htm" width="1000"></iframe></p><p>If your browser doesn’t support CSS3 Animation but support canvas, the sprite’s running animation should be displayed but the character won’t move through the width of the screen.</p><p><strong><span
style="text-decoration: underline;">Note:</span></strong> if you’d like to know more about canvas and sprites animation, you can have a look to this article: <a
href="http://blogs.msdn.com/b/davrous/archive/2011/07/21/html5-gaming-animating-sprites-in-canvas-with-easeljs.aspx">HTML5 Gaming: animating sprites in Canvas with EaselJS</a></p><h4>Delay</h4><p>The “animation-delay” property simply allows an animation to begin execution some time after it is applied.</p><h4>Events</h4><p>3 <strong>events</strong> could be raised during an animation. They are named “Animation<em>Start</em>”, “Animation<em>End</em>” and “Animation<em>Iteration</em>”. Depending on your browser, the correct name will be for instance:</p><ul><li>Chrome:<em> webkitAnimationEnd</em></li><li>Firefox: <em>mozAnimationEnd</em></li><li>Internet Explorer:<em> MSAnimationEnd</em></li></ul><p>The event will give you the following details:</p><ul><li><em>animationName</em>: name of the animation which raised the event</li><li><em>elapsedTime</em>: the amount of time the animation has been running, in seconds</li></ul><p>Here is an usage sample for IE10:</p><pre>elementToAnimate.addEventListener("MSAnimationEnd", function () {
    alert("the end !");
}, false);</pre><h3>More about CSS3 animations</h3><p>CSS3 animations are really useful for 2 main reasons:</p><ul><li><strong>Hardware acceleration:</strong> CSS3 Animations are most of the time directly handled by the GPU and could produce smoother results. This could then be a very interesting approach for mobile devices.</li><li><strong>Better separation between code and design</strong>: I know there is some debates on this point but with David, we think that a developer shouldn’t be aware of animations or anything related to design as much as possible. In the same way the designer/artist must not be aware of JavaScript. CSS3 offers then this possibility and could let the designers work with their classical tools to generate the appropriate animations on elements, between screens, etc.</li></ul><p>To highlight this importance in performance, the following HTML5 game I wrote using a full frame &lt;canvas&gt;: <a
title="http://blogs.msdn.com/b/davrous/archive/2011/09/09/html5-platformer-the-complete-port-of-the-xna-game-to-lt-canvas-gt-with-easeljs.aspx" href="http://blogs.msdn.com/b/davrous/archive/2011/09/09/html5-platformer-the-complete-port-of-the-xna-game-to-lt-canvas-gt-with-easeljs.aspx">HTML5 Platformer</a> run at 60 fps in IE9/IE10 on my PC but at 10 fps max on a iPad 2. This is because its CPU is much more limited and the iPad is currently not hardware-accelerating &lt;canvas&gt;. Using CSS3 Transitions/Animations to animate several smaller &lt;canvas&gt; elements could provide a huge performance boost for this game. Think about it when you’re targeting mobile devices!</p><h3>Browsers Support</h3><p>Since the Platform Preview 3 of IE10 available in the <a
href="http://msdn.microsoft.com/en-us/windows/apps/br229516">Windows Developer Preview</a>, we’re supporting CSS3 Animations. And as you can see on the following report produced by <a
href="http://caniuse.com/#search=CSS3%20animation">caniuse.com</a>, the CSS3 animations are now supported on a wide range of browsers:</p><p><img
class="alignnone size-full wp-image-51037" title="fig2" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/fig2.png" alt="browser support" width="761" height="275" /></p><p>But as the specification is not finished yet (<em>working draft</em>), you must use vendor’s prefixes such as –ms-, –moz-, –webkit-, –o- to make a cross-browsers compatible application.</p><p>But the question could be: how to handle browsers that don’t support this new feature?</p><p>First option is to just do nothing. Thanks to the beauty of graceful degradation, you could just let the user only see a static image if you’ve worked correctly. This is for instance the case of these 2 original samples of Anthony: <a
href="http://www.anthonycalzadilla.com/i-twitty-the-fool/">I Twitty the Fool!</a> and <a
href="http://www.anthonycalzadilla.com/css3-ATAT/">Pure CSS3 AT-AT Walker</a> . When watched in IE9, it looks like we only have a static image. When watched in IE10, the very same code shows nice animations. IE10 users will then have an enhanced version while IE9 will still be able to view and use properly the website. The more modern your browser is, the more visual bonus you will have.</p><p>The second option is to detect the feature via a JS library like Modernizr and try to offer the same animation via a JavaScript library that will mimic the animations. This is what we usually call a fallback mechanism. Unfortunately, I haven’t found today a working &amp; complete JS library that could replace CSS3 animations when not supported by the browser.</p><p>I have then written a sample JS library more or less specifically designed for the AT-AT sample.</p><h3>CSS3 Animations JavaScript fallback library</h3><p>Animations are nothing more than a series of transitions separated by a certain duration defined via the keyframes. I’ve then reused the concepts built by David Catuhe in his transitions helper library. I let you reviewing his article to check the base of the concepts behind the code.</p><p>On my side, I’ve added some support to animate the CSS3 2D Transform rotation &amp; translation values and a way to iterate through the keyframes.</p><p>Here is the main part of the library you need to review:</p><pre>// Animation object
// It need the HTML targeted element, the name of the animation, its duration &amp; iteration count and
// the keyframes contained in an array object
// View the animation simply as a sequence of transitions played a certain number of times
ANIMATIONSHELPER.animation = function (target, name, duration, iterationcount, keyframes) {
    // saving the properties values
    this.name = name;
    this.duration = duration;
    this.iterationcount = iterationcount;
    this.target = target;
&nbsp;
    var elapsedtime = 0;
    var keyframeduration = 0;
    var elapsedtime = 0;
&nbsp;
    // Transforming the percentage of each keyframe into duration value
    for (var i = 0; i &lt; keyframes.length; i++) {
        keyframeduration = ((keyframes[i].percentage * duration) / 100) - elapsedtime;
        keyframes[i].duration = keyframeduration;
        elapsedtime += keyframeduration;
    }
&nbsp;
    this.currentTransition = { isPlaying: false };
    this.keyframes = keyframes;
    this.keyframesCount = keyframes.length;
    this.currentKeyFrameIndex = 0;
&nbsp;
    // The nextTransition() function return the next transition to run
    // based on the current keyframe to play
    this.nextTransition = function (keyframe, ease, customEaseP1X, customEaseP1Y, customEaseP2X, customEaseP2Y) {
        var properties = [];
        var finalValues = [];
        var transition;
&nbsp;
        // Compared to the original TRANSITIONSHELPER of David Catuhe
        // We need a specific code to play with the CSS3 2D Transform properties values
        if (keyframe.propertyToAnimate === "transform") {
            for (var i = 0; i &lt; keyframe.transformType.length; i++) {
                properties.push(keyframe.transformType[i].type);
                if (keyframe.transformType[i].type == "rotate") {
                    finalValues.push({ deg: keyframe.transformType[i].value1 });
                }
                else {
                    finalValues.push({ x: keyframe.transformType[i].value1, y: keyframe.transformType[i].value2 });
                }
            }
&nbsp;
            // Create a new transition
            transition = {
                name: this.name + this.currentKeyFrameIndex,
                target: this.target,
                properties: properties,
                finalValues: finalValues,
                originalValues: ANIMATIONSHELPER.extractValues(target.style[ANIMATIONSHELPER.currentTransformProperty], this.name),
                duration: keyframe.duration,
                startDate: (new Date).getTime(),
                currentDate: (new Date).getTime(),
                ease: ease,
                customEaseP1X: customEaseP1X,
                customEaseP2X: customEaseP2X,
                customEaseP1Y: customEaseP1Y,
                customEaseP2Y: customEaseP2Y,
                isPlaying: true,
                type: "transform"
            };
&nbsp;
            return transition;
        }
        // If it's a classic property to animate, we're using more or less the TRANSITIONSHELPER as-is
        else {
            return TRANSITIONSHELPER.transition(this.target, keyframe.propertyToAnimate, keyframe.value, keyframe.duration, TRANSITIONSHELPER.easingFunctions.linear);
        }
    };
&nbsp;
    // each animation object has a tick function
    // that will be called every 17 ms (to target 60 fps)
    // This ticker is monitoring the current state of the transition and
    // create a new transition as soon as the old one is finished/dead
    this.tick = function () {
        if (this.iterationcount &gt; 0) {
            if (!this.currentTransition.isPlaying) {
                this.currentTransition = this.nextTransition(this.keyframes[this.currentKeyFrameIndex], ANIMATIONSHELPER.easingFunctions.linear);
                // We're using our own global ticker only for the 2D transformations
                // Otherwise, we're using the one from the TRANSITIONSHELPER library
                if (this.currentTransition.type === "transform") {
                    ANIMATIONSHELPER.currentTransitions.push(this.currentTransition);
                }
                this.currentKeyFrameIndex++;
&nbsp;
                // We've reached the last keyframe (100%). We're starting back from the beginning
                if (this.currentKeyFrameIndex &gt;= this.keyframesCount) {
                    this.currentKeyFrameIndex = 0;
                    this.iterationcount--;
                }
            }
        }
    };
};</pre><p>The first part of the code is iterating through each keyframe to compute the exact duration specified by each percentage. We’re then defining a <code>nextTransition()</code> function that will dynamically build the next transition to play based on the current index into the keyframes collection. At last, we’ve got a <code>tick()</code> function that will monitor the current state of the transition applied. Once the transition is finished or dead, it asks for the next transition, push it to the stack of transitions to be played and moves the indexes.</p><p>This <code>tick()</code> function is called thanks to this code:</p><pre>ANIMATIONSHELPER.launchAnimation = function (animation) {
    // Launching the tick service if required
    if (ANIMATIONSHELPER.tickIntervalID == 0) {
        ANIMATIONSHELPER.tickIntervalID = setInterval(ANIMATIONSHELPER.tick, 17);
    }
&nbsp;
    // Little closure to launch the tick method on the appropriate animation instance
    setInterval(function () { animation.tick(); }, 17);
};</pre><p>At last, we have this kind of code that helps us building the keyframes:</p><pre>// Object to build a new generic keyframe (not working on the CSS3 2D Transform properties thus)
ANIMATIONSHELPER.keyframe = function (percentage, propertyToAnimate, value) {
    this.percentage = percentage;
    this.propertyToAnimate = propertyToAnimate;
    this.value = value;
};
&nbsp;
//Objects to build specific rotation keyframes
ANIMATIONSHELPER.rotationkeyframe = function (percentage, value) {
    this.percentage = percentage;
    this.propertyToAnimate = "transform";
    this.transformType = [];
    this.transformType.push(new ANIMATIONSHELPER.transformType("rotate", value));
};</pre><p>To highlight its usage, let’s recreate the previous simple CSS3 Animation skull sample with this library :</p><pre>// number of times you'd like the animations to be run
var iterationsNumber = 100;
&nbsp;
var skullElement = document.getElementById("skull");
var keyframes = [];
keyframes.push(new ANIMATIONSHELPER.rotationkeyframe(25, 15));
keyframes.push(new ANIMATIONSHELPER.rotationkeyframe(50, -5));
keyframes.push(new ANIMATIONSHELPER.rotationkeyframe(55, 0));
keyframes.push(new ANIMATIONSHELPER.rotationkeyframe(75, -10));
keyframes.push(new ANIMATIONSHELPER.rotationkeyframe(100, 0));
&nbsp;
var animation1 = new ANIMATIONSHELPER.animation(skullElement, "rotate-skull", 7000,
                            iterationsNumber, keyframes);
&nbsp;
ANIMATIONSHELPER.launchAnimation(animation1, ANIMATIONSHELPER.easingFunctions.linear);</pre><p>And here is the result that will now work in every browser supporting CSS3 2D Transform:</p><p><iframe
style="border-bottom: #ffffff 0px solid; border-left: #ffffff 0px solid; border-top: #ffffff 0px solid; border-right: #ffffff 0px solid" height="200" src="http://david.blob.core.windows.net/html5/css3atat/indexSkullJS.htm" width="400" scrolling="no"></iframe></p><p>At last, the very first sample demonstrated at the beginning of this article uses Modernizr to check the support for CSS3 Animations. If it’s not the case, it loads the code that will mimic the keyframes defined in the file master.css, moz-master.css &amp; ms-master.css :</p><pre>// Checking if CSS3 animations is supported
if (!Modernizr.cssanimations) {
// if so, we can use our JS fallback library
    supportElement.innerHTML = "CSS3 Animations &lt;strong&gt;are not supported&lt;/strong&gt;";
    LoadJSAnimationsFallback();
}
else {
    // if CSS3 animation is supported, we have nothing to do.
    // The *master.css stylesheets will be automatically applied &amp; used.
    supportElement.innerHTML = "CSS3 Animations &lt;strong&gt;are supported&lt;/strong&gt;";
}</pre><p>The <em>LoadJSAnimationsFallback()</em> function is defined into <em>jsfallback-master.js</em> which simply contains all the keyframes declarations and the 19 animations needed to mimic the behavior created by Anthony in pure CSS3. In this approach, the designer then needs to rewrite all rules using the library. Another approach could be to parse one of the CSS file using an XHR call and to create dynamically the JavaScript calls to the library. This needs more work as you almost need to reimplement the CSS3 animations specifications in JavaScript!</p><p>You now have an idea on the way to build a fallback mechanism to support more browsers while starting to use the latest CSS3 specifications.</p><p>You can download the files for the main sample here: <a
title="http://david.blob.core.windows.net/html5/css3atat/CSS3ATATNonMinified.zip" href="http://david.blob.core.windows.net/html5/css3atat/CSS3ATATNonMinified.zip">http://david.blob.core.windows.net/html5/css3atat/CSS3ATATNonMinified.zip</a></p><p>It contains the unminified versions of the animationsHelper.js, transitionsHelper.js, jsfallback-master.js JavaScript files as well as the various CSS3 declinaison files for the main vendors prefixes.</p><h3>Conclusion</h3><p>CSS3 Animations is a powerful technology to push HTML5 applications to a new level. It offers interesting scenarios. Designers could use it to create a new generation of UI screens with smooth &amp; fluid animations without the need of developers. As it’s hardware-accelerated most of the time, developers should also pay attention to this specification. At last, both could collaborate. Designers could work on a series of predefined animations covering most scenarios. Developers could then create JavaScript libraries that will implement those animations. This library could offer in a transparent way 2 implementations: a dynamic generation of CSS3 on the fly or a fallback for older browsers.</p><h3>Going further</h3><ul><li>Article about CSS3 Transitions by David Catuhe: <a
href="http://blogs.msdn.com/b/eternalcoding/archive/2011/11/01/css3-transitions.aspx">Introduction to CSS3 Transitions</a></li><li>CSS3 Animations specifications: <a
title="http://www.w3.org/TR/css3-animations/" href="http://www.w3.org/TR/css3-animations/">http://www.w3.org/TR/css3-animations/</a></li><li>IE Test Drive on CSS3 animations: <a
title="http://ie.microsoft.com/testdrive/Graphics/hands-on-css3/hands-on_animations.htm" href="http://ie.microsoft.com/testdrive/Graphics/hands-on-css3/hands-on_animations.htm">http://ie.microsoft.com/testdrive/Graphics/hands-on-css3/hands-on_animations.htm</a></li></ul><p><strong>Other useful posts:</strong></p><ul><li>Events are relatively limited in the CSS3 Animation spec. Joe Lambert is proposing an interesting solution to trigger events on each keyframe: <a
href="http://blog.joelambert.co.uk/2011/05/20/css-animation-keyframe-events-javascript-solution/">CSS Animation Keyframe Events (Javascript solution)</a></li></ul><div
style="text-align:center;padding-bottom:50px;"><div
style="float:left;padding-left:30px;"> <script>GA_googleFillSlot("Edit_300x100_C");</script> </div><div
style="float:right;padding-right:30px;"> <script>GA_googleFillSlot("Edit_300x100_D");</script> </div></div><div
style="clear:both"></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/build-awesome-apps-with-css3-animations/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Browser Trends February 2012: Chrome 16 Obliterates IE8</title><link>http://www.sitepoint.com/browser-trends-february-2012/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=browser-trends-february-2012</link> <comments>http://www.sitepoint.com/browser-trends-february-2012/#comments</comments> <pubDate>Wed, 01 Feb 2012 23:00:59 +0000</pubDate> <dc:creator>Craig Buckler</dc:creator> <category><![CDATA[Mobile]]></category> <category><![CDATA[News & Trends]]></category> <category><![CDATA[Opinion]]></category> <category><![CDATA[Web Tech]]></category> <category><![CDATA[browser]]></category> <category><![CDATA[chrome]]></category> <category><![CDATA[firefox]]></category> <category><![CDATA[ie]]></category> <category><![CDATA[market]]></category> <category><![CDATA[opera]]></category> <category><![CDATA[safari]]></category> <category><![CDATA[Trends]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=50998</guid> <description><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2011/05/522-browser-trends-50x50.jpg" class="attachment-thumbnail wp-post-image" alt="522-browser-trends" title="522-browser-trends" />Craig looks at the browser market during January 2012. It's the same story: Chrome continues to blast away at the competition.]]></description> <content:encoded><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2011/05/522-browser-trends-50x50.jpg" class="attachment-thumbnail wp-post-image" alt="522-browser-trends" title="522-browser-trends" /><p></p><p>I expected <a
href="http://www.sitepoint.com/browser-trends-january-2012/">last month&#8217;s browser statistics</a> to be a little unusual. With a large proportion of the western world on vacation, the ratio of home to business usage rises. Typically, IE usage would drop and the other browsers would rise. You&#8217;d expect IE fluctuations to stop following the return to business in January. So let&#8217;s look at the latest <a
href="http://gs.statcounter.com/">worldwide StatCounter statistics</a> to see if that happened:</p><table
id="stats" summary="worldwide browser market share statistics, February 2011" width="80%" style="text-align:right !important;margin:20px auto"><tr><th
width="20%">Browser</th><th
width="20%">December</th><th
width="20%">January</th><th
width="20%">change</th><th
width="20%">relative</th></tr><tr><th>IE 9.0+</th><td>10.75%</td><td>11.45%</td><td
class="up">+0.70%</td><td
class="up">+6.50%</td></tr><tr><th>IE 8.0</th><td>22.12%</td><td>20.82%</td><td
class="dn">-1.30%</td><td
class="dn">-5.90%</td></tr><tr><th>IE 7.0</th><td>4.00%</td><td>3.63%</td><td
class="dn">-0.37%</td><td
class="dn">-9.30%</td></tr><tr><th>IE 6.0</th><td>1.78%</td><td>1.56%</td><td
class="dn">-0.22%</td><td
class="dn">-12.40%</td></tr><tr><th>Firefox 4.0+</th><td>19.81%</td><td>20.01%</td><td
class="up">+0.20%</td><td
class="up">+1.00%</td></tr><tr><th>Firefox 3.7-</th><td>5.46%</td><td>4.77%</td><td
class="dn">-0.69%</td><td
class="dn">-12.60%</td></tr><tr><th>Chrome</th><td>27.33%</td><td>28.45%</td><td
class="up">+1.12%</td><td
class="up">+4.10%</td></tr><tr><th>Safari</th><td>6.09%</td><td>6.61%</td><td
class="up">+0.52%</td><td
class="up">+8.50%</td></tr><tr><th>Opera</th><td>1.99%</td><td>1.96%</td><td
class="dn">-0.03%</td><td
class="dn">-1.50%</td></tr><tr><th>Others</th><td>0.67%</td><td>0.74%</td><td
class="up">+0.07%</td><td
class="up">+10.40%</td></tr><tr><th>IE (all)</th><td>38.65%</td><td>37.46%</td><td
class="dn">-1.19%</td><td
class="dn">-3.10%</td></tr><tr><th>Firefox (all)</th><td>25.27%</td><td>24.78%</td><td
class="dn">-0.49%</td><td
class="dn">-1.90%</td></tr></table><p>The table shows market share estimates for desktop browsers. The &#8216;change&#8217; column shows the absolute increase or decrease in market share. The &#8216;relative&#8217; column indicates the proportional change, i.e. another 12.4% of IE6 users abandoned the browser last month. Party time! There are several caveats so I recommend you read <a
href="http://blogs.sitepoint.com/how-browser-market-share-is-calculated">How Browser Market Share is Calculated</a>.<div>  <script type='text/javascript'>GA_googleFillSlot("InArticle_728x90_1");</script> </div></p><p>I previously reported that, despite widespread reports, <a
href="http://www.sitepoint.com/browser-trends-january-2012/">Chrome 15&#8242;s victory as the world&#8217;s most-used browser version</a> was short-lived. The release of Chrome 16 on December 13 2011 split the user base so IE8 quickly retained its lead.</p><p>However, we&#8217;re now at the end of Chrome 16&#8242;s life. In fact, Chrome 17 is around a week overdue so the vast majority of Chrome users &#8212; 25.79% &#8212; are using version 16 <em>(I was tempted to refer to it as &#8216;old&#8217; but it&#8217;s hardly past its prime at seven weeks of age!)</em> The next release will split Chrome&#8217;s user base again, but IE8 is losing ground too rapidly to keep up. It lost another 1.3% in January after a 1.88% drop the month before. The browser looks likely to dip below 20% during the next few weeks.</p><p>Although IE9 had a good month, overall, IE dropped 1.19%. Firefox also lost half a percent. While most of those users switched to Chrome, Safari also received a surprise boost. Did you receive a new Mac or iPad during the holidays? If so, perhaps you&#8217;re partially responsible for that half-percent jump.</p><p>Chrome is looking unbeatable. It&#8217;s monthly 1% rise is holding firm and it&#8217;s likely to overtake IE by the middle of the year.</p><h2>Mobile Browser Usage</h2><p>The mobile market remained busy during January and usage accounted for <a
href="http://gs.statcounter.com/#mobile_vs_desktop-ww-monthly-201201-201201-bar">8.49% of all web activity</a>.</p><p>The primary mobile browsing applications are:</p><ol><li>Opera Mini/Mobile &#8212; 23.34% (down 0.88%)</li><li>Android &#8212; 21.39% (up 1.17%)</li><li>iPhone &#8212; 19.51% (up 1.10%)</li><li>Nokia browser &#8212; 11.82% (down 1.10%)</li><li>Blackberry &#8212; 6.68% (down 0.85%)</li></ol><p>There&#8217;s little point reading too much into these figures; there are too many handset harlots switching phones more frequently than their underwear! The only obvious trend is Blackberry&#8217;s continuing misfortunes; but you don&#8217;t need browser statistics to see that.</p><div
style="text-align:center;padding-bottom:50px;"><div
style="float:left;padding-left:30px;"> <script>GA_googleFillSlot("Edit_300x100_C");</script> </div><div
style="float:right;padding-right:30px;"> <script>GA_googleFillSlot("Edit_300x100_D");</script> </div></div><div
style="clear:both"></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/browser-trends-february-2012/feed/</wfw:commentRss> <slash:comments>18</slash:comments> </item> <item><title>What&#8217;s New in Firefox 10</title><link>http://www.sitepoint.com/firefox-10-whats-new/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=firefox-10-whats-new</link> <comments>http://www.sitepoint.com/firefox-10-whats-new/#comments</comments> <pubDate>Wed, 01 Feb 2012 14:00:54 +0000</pubDate> <dc:creator>Craig Buckler</dc:creator> <category><![CDATA[HTML & CSS]]></category> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Open Source]]></category> <category><![CDATA[Technology]]></category> <category><![CDATA[firefox]]></category> <category><![CDATA[Firefox 10]]></category> <category><![CDATA[HTML5 Dev Center]]></category> <category><![CDATA[Mozilla]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=50995</guid> <description><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2010/05/328-firefox-4-50x50.png" class="attachment-thumbnail wp-post-image" alt="328-firefox-4" title="328-firefox-4" />It's too late to upgrade to Firefox 9 - version 10 has been released. While we're becoming used to lightweight sets of new features, Craig finds a surprising number of additions in the new browser.]]></description> <content:encoded><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2010/05/328-firefox-4-50x50.png" class="attachment-thumbnail wp-post-image" alt="328-firefox-4" title="328-firefox-4" /><p></p><p>Firefox reached double-digit version numbers on January 31, 2012. It&#8217;s been a mere <a
href="http://www.sitepoint.com/firefox-9-whats-new/">six weeks since we received Firefox 9.0</a> but there are several interesting features in the new version&hellip;</p><h2>Page Inspector</h2><p>Firefox now has it&#8217;s own built-in page inspector. To launch it, select <strong>Inspect</strong> from the <strong>Web Developer</strong> menu, point to an element and choose &#8220;Inspect&#8221; from the right-click context menu, or press Ctrl+Shift+I. The active element will be highlighted and a bar appears at the bottom of the window showing a clickable breadcrumb trail of the DOM hierarchy.</p><p>The <strong>HTML</strong> button shows the element&#8217;s location in the page source while <strong>Style</strong> displays an editable list of applied CSS rules and properties.</p><p><img
src="http://blogs.sitepointstatic.com/images/tech/633-firefox-10-inspector.png" width="600" height="580" alt="Firefox Inspector" class="center" /></p><p>Let&#8217;s be honest: it&#8217;s not <a
href="http://www.sitepoint.com/firebug-19-new-features/">Firebug</a>. But it looks good, works well and will be invaluable on those rare occasions when Firebug isn&#8217;t available. I was a little concerned the Inspector would clash with Firebug in some way but I&#8217;m yet to encounter a problem.<div>  <script type='text/javascript'>GA_googleFillSlot("InArticle_728x90_1");</script> </div></p><h2>CSS 3D Transforms</h2><p>Like the webkit browsers, Firefox 10 now supports CSS 3D transforms which allow you to rotate, skew and translate objects in three-dimensional space. You&#8217;ll require the -moz prefix but I suspect more developers will experiment with the effects now they&#8217;re supported in Firefox, Chrome, Safari and IE10.</p><h2>Fullscreen API</h2><p>The fullscreen API is another webkit feature which has been implemented in Firefox 10. You guessed correctly &#8212; it allows a page to launch the browser in full-screen mode which makes it ideal for videos, games and other interactive media.</p><p>Before hackers and pop-up advertisers become too excited, you should note that the browser places several restrictions on the feature and users cannot be placed in fullscreen mode without their knowledge or consent. The API is not particularly stable; the <a
href="http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html">W3C Fullscreen specification</a> is an early draft and there are minor differences between the webkit and gecko implementations.</p><h2>Visibility API</h2><p>The visibility API allows you to check three new document true/false properties:</p><ul><li><strong>visible</strong> &#8212; your document is the foreground tab of a non-minimized window</li><li><strong>hidden</strong> &#8212; your document is either a background tab or on a minimized window</li><li><strong>prerender</strong> &#8212; your document is being pre-rendered and is not visible to the user</li></ul><p>It&#8217;s simple but allow us to make more efficient and usable web pages. For example, changing tabs could automatically pause a video or slow down Ajax requests.</p><h2>Dynamic Forward Button</h2><p>The Forward navigation button now automatically hides itself when there&#8217;s no page to forward to! I&#8217;ve not heard anyone complain about wasted toolbar space, but it&#8217;s a logical interface enhancement since the button&#8217;s rarely used.</p><p><img
src="http://blogs.sitepointstatic.com/images/tech/633-firefox-10-forward.png" width="194" height="84" alt="Firefox hidden forward button" class="center" /></p><h2>Better Add-On Compatibility</h2><p><em>Probably</em>. Until version 10, Firefox assumed add-ons were incompatible if they were marked as valid for an earlier version. This was rarely the case and you could often force an add-on to install by changing the supported browser number. Mozilla has now reversed the policy; any extension which is compatible with Firefox 4.0 and doesn&#8217;t contain compiled code is presumed to be compatible.</p><p>Add-on issues have not been stopped completely, but the situation has improved considerably since last year.</p><p>Overall, Firefox 10 is a solid release with a good number of features. Say goodbye to version 9.0 and upgrade today &hellip; because version 11 will be with us on March 13, 2012.</p><div
style="text-align:center;padding-bottom:50px;"><div
style="float:left;padding-left:30px;"> <script>GA_googleFillSlot("Edit_300x100_C");</script> </div><div
style="float:right;padding-right:30px;"> <script>GA_googleFillSlot("Edit_300x100_D");</script> </div></div><div
style="clear:both"></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/firefox-10-whats-new/feed/</wfw:commentRss> <slash:comments>20</slash:comments> </item> <item><title>Using the HTML5 Geolocation API</title><link>http://www.sitepoint.com/using-the-html5-geolocation-api/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-the-html5-geolocation-api</link> <comments>http://www.sitepoint.com/using-the-html5-geolocation-api/#comments</comments> <pubDate>Wed, 01 Feb 2012 12:00:17 +0000</pubDate> <dc:creator>Danwei Tran Luciani</dc:creator> <category><![CDATA[HTML5]]></category> <category><![CDATA[Tutorials]]></category> <category><![CDATA[Web Tech]]></category> <category><![CDATA[geolocation]]></category> <category><![CDATA[HTML5 Dev Center]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=50946</guid> <description><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/feature-50x50.png" class="attachment-thumbnail wp-post-image" alt="feature" title="feature" />Telling your site visitors where they are can be a very smart thing to do. Microsoft Evangelist Danwei Tran Luciani explains why ... and how.]]></description> <content:encoded><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2012/02/feature-50x50.png" class="attachment-thumbnail wp-post-image" alt="feature" title="feature" /><p></p><p>Knowing the location of your users can help boost the quality of your website and the speed of your service.</p><p>In the past, users had to actively input their location and submit it to a site, either by typing it, using a long drop-down list, or clicking a map. Now, with the HTML5 Geolocation API, finding your users (with their permission) is easier than ever.</p><p><strong>Figure 1</strong> shows a website using geolocation to determine the location of a user, represented in latitude and longitude. The numbers can easily be translated into something more understandable, such as the street name or city.</p><p><img
class="alignnone size-full wp-image-50951" title="figure1" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/figure13.png" alt="showing user location" width="550" height="262" /></p><p><strong>Figure 1 Showing a User’s Location with the Help of Geolocation</strong></p><p>Imagine how useful your site could be if it provided online timetables for all public transportation in a particular city. Using geolocation, the site could recommend optimal travel routes to get people where they’re going as quickly as possible. Desktop users could get their start location sorted by proximity to their computer. Mobile users trying to get home after a night out could quickly find the closest bus stop within walking distance. These possibilities and more are just an API away.<div>  <script type='text/javascript'>GA_googleFillSlot("InArticle_728x90_1");</script> </div></p><h3>Scenarios for Using the Geolocation API</h3><p>Here are 12 simple scenarios that illustrate how a website can accommodate users and customize their experience by taking their location into account. Some of them might seem obvious, but the small things often make the biggest differences.</p><ul><li>Public transportation sites can list nearby bus stops and metro locations.</li><li>Late night out? Taxi or car service websites can find where you are, even if you don’t know.</li><li>Shopping sites can immediately provide estimates for shipping costs.</li><li>Travel agencies can provide better vacation tips for current location and season.</li><li>Content sites can more accurately determine the language and dialect of search queries.</li><li>Real estate sites can present average house prices in a particular area, a handy tool when you’re driving around to check out a neighborhood or visit open houses.</li><li>Movie theater sites can promote films playing nearby.</li><li>Online games can blend reality into the game play by giving users missions to accomplish in the real world.</li><li>News sites can include customized local headlines and weather on their front page.</li><li>Online stores can inform whether products are in stock at local retailers.</li><li>Sports and entertainment ticket sales sites can promote upcoming games and shows nearby.</li><li>Job postings can automatically include potential commute times.</li></ul><h3>How Geolocation Works</h3><p>Technically speaking, a PC or a mobile device has several ways to find out its own location (hopefully, in the same place as the user).</p><ul><li>GPS is the most accurate way to determine positioning, but it’s less energy efficient than other options and sometimes requires a lengthy startup time.</li><li>A-GPS (assistive GPS) uses triangulation between mobile phone towers and public masts to determine location. Although not as precise as GPS, A-GPS is sufficient for many scenarios.</li><li>Mobile devices that support Wi-Fi access points can use hotspots to determine the user’s location.</li><li>Stationary computers without wireless devices can obtain rough location information using known IP address ranges.</li></ul><p>When it comes to sharing the physical location of users, privacy is a serious concern. According to the Geolocation API, “user agents must not send location information to websites without the express permission of the user.” In other words, a user must always opt in to share location information with a website.</p><p><strong>Figure 2</strong> shows a typical message requesting a user’s permission. For more information about ensuring security with the Geolocation API, see <a
href="http://www.w3.org/TR/geolocation-API/#security">Security and privacy considerations</a>.</p><p><img
class="alignnone size-full wp-image-50952" title="figure2" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/figure24.png" alt="user permission request" width="550" height="56" /></p><p><strong>Figure 2 Sample User Permission Request</strong></p><h3>Three Simple Functions</h3><p>Are you ready to incorporate geolocation into your website? You need to learn only three simple functions to master the entire API, which resides within the geolocation object, an attribute of the Navigator object. Learn more about the geolocation object <a
href="http://msdn.microsoft.com/en-us/library/gg593041%28v=vs.85%29.aspx">here</a>.</p><p>The <code>getCurrentPosition</code> function gets the user location one time. It takes two arguments in the form of callbacks: one for a successful location query and one for a failed location query. The success callback takes a Position object as an argument. It optionally takes a third argument in the form of a PositionOptions object.</p><pre>navigator.geolocation.getCurrentPosition(locationSuccess, locationFail);
    function locationSuccess(position) {
        latitude = position.coords.latitude;
	longitude = position.coords.longitude;
    }
    function locationFail() {
        alert(‘Oops, could not find you.’);
    }</pre><p>The Position object contains the properties shown below.</p><p><strong>Properties of the Position Object</strong></p><table
width="100%" border="1" cellspacing="0" cellpadding="0"><tbody><tr><td
style="padding: 5px 10px;"><strong>Property</strong></td><td
style="padding: 5px 10px;"><strong>Value</strong></td><td
style="padding: 5px 10px;"><strong>Unit</strong></td></tr><tr><td
style="padding: 5px 10px;">coords.latitude</td><td
style="padding: 5px 10px;">double</td><td
style="padding: 5px 10px;">degrees</td></tr><tr><td
style="padding: 5px 10px;">coords.longitude</td><td
style="padding: 5px 10px;">double</td><td
style="padding: 5px 10px;">degrees</td></tr><tr><td
style="padding: 5px 10px;">coords.altitude</td><td
style="padding: 5px 10px;">double or null</td><td
style="padding: 5px 10px;">meters</td></tr><tr><td
style="padding: 5px 10px;">coords.accuracy</td><td
style="padding: 5px 10px;">double</td><td
style="padding: 5px 10px;">meters</td></tr><tr><td
style="padding: 5px 10px;">coords.altitudeAccuracy</td><td
style="padding: 5px 10px;">double or null</td><td
style="padding: 5px 10px;">meters</td></tr><tr><td
style="padding: 5px 10px;">coords.heading</td><td
style="padding: 5px 10px;">double or null</td><td
style="padding: 5px 10px;">degrees clockwise</td></tr><tr><td
style="padding: 5px 10px;">coords.speed</td><td
style="padding: 5px 10px;">double or null</td><td
style="padding: 5px 10px;">meters/second</td></tr><tr><td
style="padding: 5px 10px;">timestamp</td><td
style="padding: 5px 10px;">DOMTimeStamp</td><td
style="padding: 5px 10px;">like the Date object</td></tr></tbody></table><p>The <code>watchPosition</code> function keeps polling for user position and returns an associated ID. The device determines the rate of updates and pushes changes in location to the server.</p><p>The <code>clearWatch</code> function stops polling for user position. It takes the ID of <code>watchPosition</code> as an argument.</p><h3>Presenting Location Data: Geodetic or Civic</h3><p>There are two ways of presenting location data to the user: geodetic and civil. The geodetic way of describing position refers directly to latitude and longitude. The civic representation of location data is a more human readable and understandable format.</p><p>Each parameter has both a geodetic representation and a civic representation, as illustrated below.</p><p><strong>Examples of Geodetic and Civic Data</strong></p><table
width="100%" border="1" cellspacing="0" cellpadding="10"><tbody><tr><td
style="padding: 5px 10px;" valign="top"><strong>Attribute</strong></td><td
style="padding: 5px 10px;" valign="top"><strong>Geodetic</strong></td><td
style="padding: 5px 10px;" valign="top"><strong>Civic</strong></td></tr><tr><td
style="padding: 5px 10px;" valign="top">Position</td><td
style="padding: 5px 10px;" valign="top">59.3, 18.6</td><td
style="padding: 5px 10px;" valign="top">Stockholm</td></tr><tr><td
style="padding: 5px 10px;" valign="top">Elevation</td><td
style="padding: 5px 10px;" valign="top">10 meters</td><td
style="padding: 5px 10px;" valign="top">4<sup>th</sup> floor</td></tr><tr><td
style="padding: 5px 10px;" valign="top">Heading</td><td
style="padding: 5px 10px;" valign="top">234 degrees</td><td
style="padding: 5px 10px;" valign="top">To the city center</td></tr><tr><td
style="padding: 5px 10px;" valign="top">Speed</td><td
style="padding: 5px 10px;" valign="top">5 km / h</td><td
style="padding: 5px 10px;" valign="top">Walking</td></tr><tr><td
style="padding: 5px 10px;" valign="top">Orientation</td><td
style="padding: 5px 10px;" valign="top">45 degrees</td><td
style="padding: 5px 10px;" valign="top">North-East</td></tr></tbody></table><p>When using the Geolocation API, you get the geodetic data back from the functions. Presenting location data in raw numbers is rarely friendly or useful. Online services, such as <a
href="http://www.bing.com/community/site_blogs/b/maps/archive/2010/08/31/batch-geocoding-and-batch-reverse-geocoding-with-bing-maps.aspx">Bing Maps</a> and Yahoo GeoPlanet can help you translate between the two presentation modes.</p><h3>Browser Support</h3><table
width="100%" border="1" cellspacing="0" cellpadding="0"><tbody><tr><td><img
class="aligncenter size-full wp-image-50956" style="margin-top: 10px;" title="ie" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/ie.png" alt="IE" width="100" height="100" /></td><td><img
class="aligncenter size-full wp-image-50957" style="margin-top: 10px;" title="ff" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/ff.png" alt="FF" width="100" height="100" /></td><td><img
class="aligncenter size-full wp-image-50958" style="margin-top: 10px;" title="ch" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/ch.png" alt="Chrome" width="100" height="100" /></td><td><img
class="aligncenter size-full wp-image-50959" style="margin-top: 10px;" title="op" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/op.png" alt="Opera" width="100" height="100" /></td></tr><tr><td
style="text-align: center;">Internet Explorer 9+</td><td
style="text-align: center;">Firefox 3.5+</td><td
style="text-align: center;">Chrome 5+</td><td
style="text-align: center;">Opera 10.6+</td></tr><tr><td><img
class="aligncenter size-full wp-image-50960" style="margin-top: 10px;" title="sf" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/sf.png" alt="Safari" width="100" height="100" /></td><td><img
class="aligncenter size-full wp-image-50961" style="margin-top: 10px;" title="ip" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/ip.png" alt="iPhone" width="100" height="100" /></td><td><img
class="aligncenter size-full wp-image-50962" style="margin-top: 10px;" title="an" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/an.png" alt="Android" width="100" height="111" /></td><td><img
class="aligncenter size-full wp-image-50963" style="margin-top: 10px;" title="wp" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/wp.png" alt="Windows Phone" width="100" height="91" /></td></tr><tr><td
style="text-align: center;">Safari 5+</td><td
style="text-align: center;">iPhone 3+</td><td
style="text-align: center;">Android 2+</td><td
style="text-align: center;">Windows Phone 7.5+</td></tr></tbody></table><h3>Browsers that support the HTML5 Geolocation API</h3><p>Even though geolocation works in all the major browsers, you still have to take into account the scenarios in which location can’t be provided. For example, a user might be running an older browser or have hardware that doesn’t include positioning devices, or simply might not want to automatically share location information. The location detected could even be incorrect. In such situations, you should always include an alternative or a fallback method so users can enter or change their location manually.</p><h3>Geolocation in Action</h3><p>Copy and paste the example code below and save it as an HTML file. Open it in your favorite browser and follow the two-step instructions on the website to see the Geolocation API draw a blue circle around your current location.</p><p><strong>Using the Geolocation API</strong></p><pre>&lt;!doctype html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;title&gt;Geolocation demo&lt;/title&gt;
    &lt;meta charset="utf-8" /&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Geolocation demo&lt;/h1&gt;
    &lt;p&gt;
        Find out approximately where you are.
    &lt;/p&gt;
    &lt;p&gt;
        Step 1: &lt;button onclick="GetMap()"&gt;Show map&lt;/button&gt;
    &lt;/p&gt;
    &lt;p&gt;
        Step 2: When prompted, allow your location to be shared to see Geolocation in action
    &lt;/p&gt;
    &lt;div id="mapDiv" style="position: relative; width: 800px; height: 600px;"&gt;&lt;/div&gt;
    &lt;script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;
        var map = null;
        function GetMap() {
            /* Replace YOUR_BING_MAPS_KEY with your own credentials.
            Obtain a key by signing up for a developer account at
            http://www.microsoft.com/maps/developers/ */
        var cred = "YOUR_BING_MAPS_KEY";
        // Initialize map
        map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),
           { credentials: cred });
        // Check if browser supports geolocation
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(locateSuccess, locateFail);
        }
        else {
            alert('I\'m sorry, but Geolocation is not supported in your current browser.');
        }
    }
    // Successful geolocation
    function locateSuccess(loc) {
        // Set the user's location
        var userLocation = new Microsoft.Maps.Location(loc.coords.latitude, loc.coords.longitude);
        // Zoom in on user's location on map
        map.setView({ center: userLocation, zoom: 17 });
        // Draw circle of area where user is located
        var locationArea = drawCircle(userLocation);
        map.entities.push(locationArea);
    }
    // Unsuccessful geolocation
    function locateFail(geoPositionError) {
        switch (geoPositionError.code) {
            case 0: // UNKNOWN_ERROR
                alert('An unknown error occurred, sorry');
                break;
            case 1: // PERMISSION_DENIED
                alert('Permission to use Geolocation was denied');
                break;
            case 2: // POSITION_UNAVAILABLE
                alert('Couldn\'t find you...');
                break;
            case 3: // TIMEOUT
                alert('The Geolocation request took too long and timed out');
                break;
            default:
        }
    }
    // Draw blue circle on top of user's location
    function drawCircle(loc) {
        var radius = 100;
        var R = 6378137;
        var lat = (loc.latitude * Math.PI) / 180;
        var lon = (loc.longitude * Math.PI) / 180;
        var d = parseFloat(radius) / R;
        var locs = new Array();
        for (x = 0; x &lt;= 360; x++) {
            var p = new Microsoft.Maps.Location();
            brng = x * Math.PI / 180;
            p.latitude = Math.asin(Math.sin(lat) * Math.cos(d) + Math.cos(lat) * Math.sin(d) * Math.cos(brng));
            p.longitude = ((lon + Math.atan2(Math.sin(brng) * Math.sin(d) * Math.cos(lat), Math.cos(d) - Math.sin(lat) * Math.sin(p.latitude))) * 180) / Math.PI;
            p.latitude = (p.latitude * 180) / Math.PI;
            locs.push(p);
        }
        return new Microsoft.Maps.Polygon(locs, { fillColor: new Microsoft.Maps.Color(125, 0, 0, 255), strokeColor: new Microsoft.Maps.Color(0, 0, 0, 255) });
    }
  &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</pre><p>If you run the code as is, your location will be shown along with a message about invalid credentials, as shown in <strong>Figure 3</strong>. To get a result without the warning text (<strong>Figure 4</strong>), you need to replace <code>YOUR_BING_MAPS_KEY</code> with your own key, which is generated when you sign up for a <a
href="http://www.microsoft.com/maps/developers/web.aspx">Bing Maps Developer account</a>.</p><p><img
class="alignnone size-full wp-image-50953" title="figure3" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/figure31.png" alt="mapping without a valid key" width="550" height="413" /></p><p><strong>Figure 3 Geolocation Demo Mapping a Location without a Valid Key</strong></p><p><img
class="alignnone size-full wp-image-50954" title="figure4" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/figure42.png" alt="mapping a location with a valid key" width="550" height="414" /></p><p><strong>Figure 4 Geolocation Demo Mapping a Location after Inserting a Valid Key</strong></p><p>To see other examples of geolocation, which map your location using a push pin, visit <a
href="http://ie.microsoft.com/testdrive/HTML5/Geolocation/Default.html">IE Test Drive</a> or attend an <a
href="http://www.beautyoftheweb.com/#/camps">HTML5 Web Camp</a>.</p><p>Learn more about geolocation here:</p><ul><li><a
href="http://msdn.microsoft.com/library/gg589502%28v=VS.85%29.aspx">How to Create a Location Aware Web-Site</a></li><li><a
href="http://blogs.msdn.com/b/ie/archive/2011/02/17/w3c-geolocation-api-in-ie9.aspx">W3C Geolocation API in IE9/10</a></li><li><a
href="http://dev.w3.org/geo/api/spec-source.html">W3C Geolocation API Spec</a></li></ul><div
style="text-align:center;padding-bottom:50px;"><div
style="float:left;padding-left:30px;"> <script>GA_googleFillSlot("Edit_300x100_C");</script> </div><div
style="float:right;padding-right:30px;"> <script>GA_googleFillSlot("Edit_300x100_D");</script> </div></div><div
style="clear:both"></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/using-the-html5-geolocation-api/feed/</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>DealFuel is Here</title><link>http://www.sitepoint.com/dealfuel-is-here/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=dealfuel-is-here</link> <comments>http://www.sitepoint.com/dealfuel-is-here/#comments</comments> <pubDate>Wed, 01 Feb 2012 02:53:38 +0000</pubDate> <dc:creator>Mick Gibson</dc:creator> <category><![CDATA[Business]]></category> <category><![CDATA[Design]]></category> <category><![CDATA[General]]></category> <category><![CDATA[graphic design]]></category> <category><![CDATA[Tech]]></category> <category><![CDATA[Web Tech]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=50919</guid> <description><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/twitter-avatar_reasonably_small1-50x50.png" class="attachment-thumbnail wp-post-image" alt="dealfuel.com" title="dealfuel.com" />DealFuel is here. The best thing to happen since bearded dragons learnt how to play ant crusher :) And we&#8217;re kicking things off with 4 cool tech deals for: Web devs who want to profit from their talent jQuery wanna-bees and students Designers who are keen to work faster Website owners who demand peace-of-mind There&#8217;s something for everyone! We [...]]]></description> <content:encoded><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/twitter-avatar_reasonably_small1-50x50.png" class="attachment-thumbnail wp-post-image" alt="dealfuel.com" title="dealfuel.com" /><p></p><p><a
href="http://www.dealfuel.com" target="_blank">DealFuel is here</a>. The best thing to happen since <a
href="http://www.youtube.com/watch?feature=player_embedded&amp;v=WTpldq3myV0" target="_blank">bearded dragons learnt how to play ant crusher</a> :) And we&#8217;re kicking things off with 4 cool tech deals for:</p><ul><li><strong>Web devs who want to profit from their talent</strong></li><li><strong>jQuery wanna-bees and students</strong></li><li><strong>Designers who are keen to work faster</strong></li><li><strong>Website owners who demand peace-of-mind</strong></li></ul><p>There&#8217;s something for everyone!</p><p><a
href="http://www.dealfuel.com"><img
class="aligncenter size-full wp-image-50922" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/dealfuel.jpg" alt="dealfuel.com" width="450" height="435" /></a></p><p>We look forward to <a
href="http://www.dealfuel.com" target="_blank">seeing you on DealFuel</a>, and welcome your feedback and comments (below)</p><div
style="text-align:center;padding-bottom:50px;"><div
style="float:left;padding-left:30px;"> <script>GA_googleFillSlot("Edit_300x100_C");</script> </div><div
style="float:right;padding-right:30px;"> <script>GA_googleFillSlot("Edit_300x100_D");</script> </div></div><div
style="clear:both"></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/dealfuel-is-here/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item><div><div
class="post_box two_ads" style="float:left;padding-left:2px;"> <script>GA_googleFillSlot("Edit_728x90_2");</script> </div></div><div
class="clear">&nbsp;</div> <item><title>What&#8217;s on at PHPMaster?</title><link>http://www.sitepoint.com/whats-on-at-phpmaster/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=whats-on-at-phpmaster</link> <comments>http://www.sitepoint.com/whats-on-at-phpmaster/#comments</comments> <pubDate>Tue, 31 Jan 2012 15:00:35 +0000</pubDate> <dc:creator>Aaron Osteraas</dc:creator> <category><![CDATA[Web Tech]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=50918</guid> <description><![CDATA[<img
width="50" height="21" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/phpmaster.-50x21.png" class="attachment-thumbnail wp-post-image" alt="phpmaster." title="phpmaster." />We&#8217;ve been busy over at PHPMaster, working to bring you the best articles and tutorials so you can get to know one of the most widely used languages on the Web Under the Hood of Yii’s Component Architecture, Part 1 This is Part 1 of a 3-part series that shows you some of the inner-workings [...]]]></description> <content:encoded><![CDATA[<img
width="50" height="21" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/phpmaster.-50x21.png" class="attachment-thumbnail wp-post-image" alt="phpmaster." title="phpmaster." /><p></p><p>We&#8217;ve been busy over at PHPMaster, working to bring you the best articles and tutorials so you can get to know one of the most widely used languages on the Web<span
id="more-50918"></span></p><h2><a
href="http://phpmaster.com/yii-under-the-hood-1/">Under the Hood of Yii’s Component Architecture, Part 1</a></h2><p>This is Part 1 of a 3-part series that shows you some of the inner-workings of the Yii Framework’s component architecture. In this part you’ll learn how Yii’s CComponent class uses PHP’s magic __get() and __set() functions to take advantage of the benefits of getter and setter methods while still allowing access to properties as if they were public variables.</p><hr
/><h2><a
href="http://phpmaster.com/pagination-with-codeigniter/">Pagination with CodeIgniter</a></h2><p>Pagination is useful when displaying a large dataset which might have hundreds results and provides a much nicer user experience. In this tutorial, you’ll learn how to use CodeIgniter’s pagination library to create a paginated list of results from a MySQL database.</p><hr
/><h2><a
href="http://phpmaster.com/bending-xml-to-your-will/">Bending XML to Your Will</a></h2><p>Extensible Markup Language (XML) is a big building block of today’s web with hundreds of XML-based languages having been developed, including XHTML, ATOM, and SOAP just to name a few. Knowing how to process XML data is a crucial programming skill today, and thankfully, PHP offers multiple ways to work with it. In this article you’ll learn what XML is and how to use the XML Parser and SimpleXML extensions to parse it.<div>  <script type='text/javascript'>GA_googleFillSlot("InArticle_728x90_1");</script> </div></p><hr
/><h2><a
href="http://phpmaster.com/liskov-substitution-principle/">The Liskov Substitution Principle</a></h2><p>The hard fight against mean machines that enjoy enslaving humans and using them like plain batteries will hopefully end up in a resounding triumph… if only Neo adheres to the Liskov Substitution Principle.</p><hr
/><h2><a
href="http://phpmaster.com/rapid-application-development-with-cakephp/">Rapid Application Development with CakePHP</a></h2><p>CakePHP is a framework that provides a solid MVC base for PHP development, allowing users at all skill levels rapidly develop robust web applications. In this article you’ll learn about two of CakePHP’s most useful features: automatic code generation with Bake, and dynamic scaffolding.</p><hr
/><div
style="text-align:center;padding-bottom:50px;"><div
style="float:left;padding-left:30px;"> <script>GA_googleFillSlot("Edit_300x100_C");</script> </div><div
style="float:right;padding-right:30px;"> <script>GA_googleFillSlot("Edit_300x100_D");</script> </div></div><div
style="clear:both"></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/whats-on-at-phpmaster/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>How to Put Your CSS3 on :target</title><link>http://www.sitepoint.com/css3-target-selector/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=css3-target-selector</link> <comments>http://www.sitepoint.com/css3-target-selector/#comments</comments> <pubDate>Mon, 30 Jan 2012 12:56:51 +0000</pubDate> <dc:creator>Craig Buckler</dc:creator> <category><![CDATA[CSS Tutorials]]></category> <category><![CDATA[HTML & CSS]]></category> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript & CSS]]></category> <category><![CDATA[CSS]]></category> <category><![CDATA[CSS3]]></category> <category><![CDATA[HTML5 Dev Center]]></category> <category><![CDATA[HTML5 Tutorials & Articles]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=50855</guid> <description><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/630-css3-target-50x50.png" class="attachment-thumbnail wp-post-image" alt="630-css3-target" title="630-css3-target" />Craig's latest tutorial looks at the CSS3 :target selector, a powerful pseudo-class hidden in the depths of the W3C specifications which you may have missed...]]></description> <content:encoded><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/630-css3-target-50x50.png" class="attachment-thumbnail wp-post-image" alt="630-css3-target" title="630-css3-target" /><p></p><p>CSS pseudo-classes which change styles in response to user actions have been with us for many years. You&#8217;ve almost certainly used :hover, :active and :focus; I can <em>(only just)</em> remember the excitement of changing IE4&#8242;s link colors back in 1997.</p><p>CSS3 also introduced :target; a powerful pseudo-class which can reduce the need for scripting in interactive widgets. Consider a page URL such as http://mysite.com/page<strong>#mytarget</strong>; an element with the id &#8220;mytarget&#8221; can have matching :target styles applied.</p><h2>:target Browser Support</h2><p>All modern browsers support :target and you won&#8217;t experience problems with IE9 or most versions of Chrome, Firefox, Safari and Opera. Unfortunately, that still leaves us with the older versions of IE. I wouldn&#8217;t worry too much about IE6 and 7, but <a
href="http://www.sitepoint.com/browser-trends-january-2012/">IE8 remains the world&#8217;s most used browser version</a>. All is not lost, however, since shims such as <a
href="http://selectivizr.com/">selectivizr</a> can add :target support without requiring complex workarounds.</p><h2>A Simple Document :target</h2><p>We&#8217;ve recently been discussing <a
href="http://www.sitepoint.com/how-to-guarantee-client-payment/">website contracts</a>. Generic contract small print such as payment schedules, hosting conditions, cancellation terms, support policies, glossaries etc. could be contained in one or more web pages. The document could grow to a considerable length even if you try and keep it concise!<div>  <script type='text/javascript'>GA_googleFillSlot("InArticle_728x90_1");</script> </div></p><p>Let&#8217;s look at a snippet of the document&#8217;s HTML5 in <em>contract.html</em>:</p><pre><code>
&lt;h1&gt;Website Contract&lt;/h1&gt;
&lt;nav&gt;
	&lt;ul&gt;
		&lt;li&gt;&lt;a href=&quot;#payment&quot;&gt;Payment Schedule&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href=&quot;#support&quot;&gt;Support &amp;amp; Maintenance&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href=&quot;#hosting&quot;&gt;Hosting Terms&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href=&quot;#glossary&quot;&gt;Glossary&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;
&lt;/nav&gt;
&lt;article id=&quot;payment&quot;&gt;
&lt;h2&gt;Payment Schedule&lt;/h2&gt;
&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/p&gt;
&lt;/article&gt;
&lt;article id=&quot;support&quot;&gt;
&lt;h2&gt;Support &amp;amp; Maintenance&lt;/h2&gt;
&lt;p&gt;Ut euismod tempor porttitor.&lt;/p&gt;
&lt;/article&gt;
&lt;article id=&quot;hosting&quot;&gt;
&lt;h2&gt;Hosting Terms&lt;/h2&gt;
&lt;p&gt;Suspendisse ac nisl lorem, ut fermentum erat.&lt;/p&gt;
&lt;/article&gt;
&lt;article id=&quot;glossary&quot;&gt;
&lt;h2&gt;Glossary&lt;/h2&gt;
&lt;p&gt;Aenean id nibh eget nisl blandit hendrerit lobortis ac tortor.&lt;/p&gt;
&lt;/article&gt;
</code></pre><p>We can use the :target attribute to highlight active sections, e.g.</p><pre><code>
article:target
{
	background-color: #ffc;
	border: 2px solid #fcc;
}
</code></pre><p>Anyone <a
href="http://blogs.sitepointstatic.com/examples/tech/css3-target/document.html"><strong>viewing the contract</strong></a> can click a navigation menu item to highlight the appropriate section. You can also issue direct links to clients who require specific information, e.g. <a
href="http://blogs.sitepointstatic.com/examples/tech/css3-target/document.html#support"><strong>contract.html#support</strong></a>.</p><p>The :target selector offers further versatility &#8212; it&#8217;s possible to create dynamic effects in HTML5 and CSS without using JavaScript. Further SitePoint articles are coming soon&hellip;</p><div
style="text-align:center;padding-bottom:50px;"><div
style="float:left;padding-left:30px;"> <script>GA_googleFillSlot("Edit_300x100_C");</script> </div><div
style="float:right;padding-right:30px;"> <script>GA_googleFillSlot("Edit_300x100_D");</script> </div></div><div
style="clear:both"></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/css3-target-selector/feed/</wfw:commentRss> <slash:comments>20</slash:comments> </item> <item><title>Responsive Web Design</title><link>http://www.sitepoint.com/responsive-web-design/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=responsive-web-design</link> <comments>http://www.sitepoint.com/responsive-web-design/#comments</comments> <pubDate>Mon, 30 Jan 2012 12:30:21 +0000</pubDate> <dc:creator>Katrien De Graeve</dc:creator> <category><![CDATA[HTML & CSS]]></category> <category><![CDATA[HTML5]]></category> <category><![CDATA[Responsive Web Design]]></category> <category><![CDATA[Web Design Tutorials & Articles]]></category> <category><![CDATA[Web Tech]]></category> <category><![CDATA[HTML5 Dev Center]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=50784</guid> <description><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/rwd1-50x50.png" class="attachment-thumbnail wp-post-image" alt="rwd" title="rwd" />Belgian Microsoft evangelist Katrien De Graeve lays out just what can be achieved with media queries in CSS.]]></description> <content:encoded><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/rwd1-50x50.png" class="attachment-thumbnail wp-post-image" alt="rwd" title="rwd" /><p></p><p>It all started with <a
href="http://www.alistapart.com/articles/responsive-web-design/">Responsive Web Design</a>, an article by Ethan Marcotte on A List Apart. Essentially, the article proposed addressing the ever-changing landscape of devices, browsers, screen sizes and orientations by creating flexible, fluid and adaptive Websites. Instead of responding to today’s needs for a desktop web version adapted to the most common screen resolution, along with a particular mobile version (often specific to a single mobile device), the idea is to approach the issue the other way around: use flexible and fluid layouts that adapt to almost any screen.</p><p><strong>Core Concepts</strong></p><p>Three key technical features are at the heart of responsive web design:</p><ul><li>Media queries and media query listeners</li><li>A flexible grid-based layout that uses relative sizing</li><li>Flexible images and media, through dynamic resizing or CSS</li></ul><p>Truly responsive web design requires all three features to be implemented.</p><p>The key point is adapting to the user’s needs and device capabilities. Suppose a mobile user will be viewing your site on a small screen. Taking the user’s needs into account doesn’t just mean adapting your content to the screen size. It also means thinking about what that mobile user will require first when visiting your site and then laying out the content accordingly. Maybe you’ll present the information in a different order. Don’t assume the user won’t need access to all the site information because she’s on a mobile device. You might need to change the fonts or interaction areas to respond better to a touch environment. All these factors influence responsive web design.<div>  <script type='text/javascript'>GA_googleFillSlot("InArticle_728x90_1");</script> </div></p><p>While mobile devices are changing the display landscape, with the appearance of more and more small screens, don’t forget what’s happening at the other end of the spectrum. Displays are also getting larger and larger. Having to serve both segments shouldn’t stop designers from being innovative on either.</p><h3>Media Queries</h3><p>Starting with CSS 2.1, media types were used to apply CSS for both screen and print. You might remember these media types:</p><pre>&lt;link rel="stylesheet" type="text/css" href="style.css" media="screen" /&gt;
&lt;link rel="stylesheet" type="text/css" href="printfriendly.css" media="print" /&gt;</pre><p>That was it! Luckily, the W3C improved <a
href="http://www.w3.org/TR/css3-mediaqueries/">media queries</a> in CSS3, moving them a big step forward.</p><p>Today, you can use media queries to scope styles to specific capabilities, applying different styles based on the capabilities that match your query. You can even combine queries that test for several features by using semantic operators such as AND and NOT). Features include width, height, max-width, max-height, device-height, orientation, aspect-ratio, resolution and more.</p><p>There are three ways to implement media queries:</p><ol><li>Use the @import rule to import style rules from other style sheets:</li><li>@import url(style600min.css) screen and (min-width: 600px);</li><li>Put media queries directly in the style sheet, as shown below.</li></ol><pre>#nav
    {
        float: right;
    }
        #nav ul
        {
            list-style: none;
        }
    @media screen and (min-width: 400px) and (orientation: portrait)
        {
            #nav li
            {
                float: right;
                margin: 0 0 0 .5em;
                border:1px solid #000000;
            }
        }
    @media screen and (min-width: 800px)
        {
            #nav
            {
                width: 200px;
            }
                #nav li
                {
                    float: left;
                    margin: 0 0 0 .5em;
                    border: none;
                }
        }</pre><p>Include a query in a linked style sheet’s <code>media</code> attribute:</p><p><code>&lt;link rel="stylesheet" type="text/css" media="screen and (max-device-width: 800px)" href="style800.css" <strong>/&gt;</strong></code><br
/> &nbsp;<br
/> Because of the (cascading) nature of CSS, default styles are defined at the top with the media query matching rules and styles below. Styles defined at the top will be cascaded to the matching styles in the rule, or even completely overwritten.</p><p>The following images present an example of a responsive web design approach that uses media queries.</p><p><strong>Figure 1</strong> and <strong>Figure 2</strong> both show a desktop using Internet Explorer 9 in two different resolutions. <strong>Figure 3</strong> shows the same responsive site on a Windows Phone, also with Internet Explorer 9.</p><p><img
class="alignnone size-full wp-image-50787" title="figure1" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/figure12.png" alt="navigation appears on the left" width="550" height="329" /><br
/> <strong>Figure 1 Navigation Appears on the Left</strong><br
/> &nbsp;<br
/> <img
class="alignnone size-full wp-image-50788" title="figure2" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/figure23.png" alt="navigation switches to the top" width="550" height="523" /><br
/> <strong>Figure 2 In an 800&#215;600 Resized Window, Navigation Switches to the Top</strong><br
/> &nbsp;<br
/> <img
class="alignnone size-full wp-image-50789" title="figure3" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/figure3.png" alt="on a windows phone" width="302" height="548" /><br
/> <strong>Figure 3 The Same Site on a Windows Phone</strong><br
/> &nbsp;<br
/> If you’re looking for some great examples of responsive web design that take full advantage of media queries, the <a
href="http://mediaqueri.es/">http://mediaqueri.es/</a> enthusiast site can be addictive, as <strong>Figure 4</strong> shows.</p><p><img
class="alignnone size-full wp-image-50790" title="figure4" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/figure41.png" alt="screenshot of media queries fan site" width="550" height="366" /></p><p><strong>Figure 4 A Collection of Sites That Use Media Queries</strong></p><h3>Media Query Listeners</h3><p>Taking media queries a step further, the CSS Object Model (CSSOM) working group at the W3C also created media query listeners, which provide an API for responding to media query changes. Instead of having to poll for changes or load several versions of a resource, you can use the API, for example, to download images only of a particular size when a media query match is triggered.</p><p>Today, <a
href="http://www.mozilla.org/en-US/firefox/">Firefox</a> and the <a
href="http://msdn.microsoft.com/ie/hh272903#_DOMMediaQuery">Internet Explorer 10 Platform Preview</a> implement media query listeners; you can see the demo “<a
href="http://ie.microsoft.com/testdrive/HTML5/CSS3MediaQueries/Default.html#MediaQueryListeners">CSS3 Media Queries &amp; Media Query Listeners</a>” on the IE Test Drive.</p><h3>A Word about the Viewport</h3><p>When testing media queries on mobile browsers, you might notice that the correct media queries are not actually being applied. When this happens, the mobile browser is doing some work on your behalf to render the page optimally on the smaller screen.</p><p>So do you think there isn’t a way of getting the real resolution? Actually there is, in the viewport meta tag. The viewport meta tag controls the logical dimensions and scaling of the mobile browser’s (chrome-less) window. Setting the width equal to the device-width works around the problem:</p><p><code>&lt;meta name="viewport" content="width=device-width"&gt;</code><br
/> &nbsp;<br
/> Other viewport settings include <code>maximum-zoom</code> and <code>initial-scale</code>.</p><h3>Flexible Grids</h3><p>A flexible grid-based layout is one of the cornerstones of responsive design. The term “grid” is used rather freely and doesn’t imply a requirement to implement any of the available grid frameworks. What it means here is using CSS for positioning and for laying out margins and spacing, and for implementing various <a
href="http://sixrevisions.com/web_design/a-guide-on-layout-types-in-web-design/">web layout types</a> in a new way. Layouts and text sizes are typically expressed in pixels. Designers love pixels. Photoshop loves pixels. But a pixel can be one dot on one device and eight dots on another. So how do you approach responsive web design if everything is pixel-based? You might not like the answer: You stop using pixel-based layouts and start using percentages or the <code>em</code> for sizing.</p><p>By basing text sizes, widths and margins on percentages or on the <code>em</code>, a unit of measurement based on a font’s point size, you can turn a fixed size into a relative size. This means you’ll need to do a little math to achieve a flexible grid and text size system. But the formula for calculating the <code>em</code> is very simple:</p><p><code>target ÷ context = result</code><br
/> &nbsp;<br
/> Let’s say the normal context for the body font size is 16 pixels. If the designer specifies that the H1 should be 24 pixels, you can calculate the following:</p><p><code>24 ÷ 16 = 1.5</code><br
/> &nbsp;<br
/> This results in the following CSS style:</p><pre>h1{
    font-size: 1.5em;
}</pre><p>&nbsp;</p><p>Always take the context into account. Continuing with the previous example, if you have an element inside the <code>H1</code> that needs to be 12 pixels, you use the current <code>H1</code> as the context. The context is now 24 pixels, so the context calculation for “H1 a” is:</p><p><code>12 ÷ 24 = 0.5</code><br
/> &nbsp;</p><p>And the CSS style is:</p><pre>h1 a{
    font-size: 0.5em;
}</pre><p>&nbsp;<br
/> You can also use percentages. The calculation algorithm is the same; you just end up with percentages.</p><p>Flexible grids use this approach. You can find several frameworks to help you craft your grid, such as <a
href="http://fluid.newgoldleaf.com/">Fluid Grid System</a> or <a
href="http://www.designinfluences.com/fluid960gs/">Fluid 960 Grid System</a> (a fluid version of 960 Grid System). Moreover, several groups within the W3C have submitted new specs for better flexible grids, with some useful results.</p><h3>CSS3 Grid Layout</h3><p>The <a
href="http://dev.w3.org/csswg/css3-grid-align/">CSS3 Grid Layout</a> (also known as Grid Alignment or, simply, the Grid), brings a typical grid system to CSS, similar to what XAML or Silverlight developers may be familiar with. At the time of this writing, the spec is an “Editor’s Draft.” It allows for defining regions in a layout, with columns and rows, spanning, spacing, padding, grid templates and more, enforcing full separation of concerns between HTML elements and CSS. Unlike HTML tables that are content, the Grid allows for placing HTML primitives into grid regions separate from actual content.</p><p>Combining the CSS3 Grid with media queries creates a powerful solution for building fluid, responsive applications.</p><p>How does the Grid work? You start by setting the display block to ‘grid’. (You need to use CSS vendor prefixes because this is not yet a CSS3 recommendation. Right now, only Internet Explorer 10 Platform Preview supports the spec, so you’ll see the CSS vendor prefix -ms- used here.) Let’s look at three examples of how you can set up different views depending on screen size. Media queries are used to apply different grid styles depending on the screen width.</p><p>In the first example, the HTML for defining the content consists of one header and three different blocks of text.</p><pre>&lt;div id="mygrid"&gt;
    &lt;header id="myheader"&gt;
        &lt;h1&gt;Hello world&lt;/h1&gt;
    &lt;/header&gt;
    &lt;div id="block1"&gt;
        &lt;h2&gt;Lorem Ipsum section 1&lt;/h2&gt;
        &lt;p&gt;
            Phasellus venenatis sem vel velit tincidunt tincidunt.
              Curabitur gravida, ante sit amet [... ...]
        &lt;/p&gt;
    &lt;/div&gt;
    &lt;div id="block2"&gt;
        &lt;h2&gt;Lorem Ipsum section 2&lt;/h2&gt;
        &lt;p&gt;
        Nam tempus justo eu massa ultrices eget imperdiet ligula placerat.
        Suspendisse [... ...].
        &lt;/p&gt;
    &lt;/div&gt;
    &lt;div id="block3"&gt;
        &lt;h2&gt;Lorem Ipsum section 3&lt;/h2&gt;
        &lt;ul&gt;
            &lt;li&gt;Curabitur ultrices tristique purus, sed pellentesque
               magna scelerisque ut.&lt;/li&gt;
            &lt;li&gt;[... ...] &lt;/li&gt;
        &lt;/ul&gt;
    &lt;/div&gt;
&lt;/div&gt;</pre><p>You start by laying out the blocks of content under each other so that the content fits smartphones.</p><pre>@media only screen and (max-width : 480px) {
    #mygrid {
        display: -ms-grid;
        margin: 3px;
        -ms-grid-columns: 100%; /*one column taking full width */
        -ms-grid-rows: 70px auto auto auto; /*4 rows */
    }
    #myheader {
       -ms-grid-row: 1;
       -ms-grid-column: 1;
    }
    #block1 {
        -ms-grid-row: 2; /*place into row 2 / column 1*/
        -ms-grid-column: 1;
    }
    #block2 {
        -ms-grid-row: 3;
        -ms-grid-column: 1;
    }
    #block3 {
        -ms-grid-row: 4;
        -ms-grid-column: 1;
    }
}</pre><p>&nbsp;</p><p>You can add background colors as shown in <strong>Figure 5</strong> to make it clearer that you’re working with grid items.</p><p><img
class="alignnone size-full wp-image-50791" title="figure5" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/figure51.png" alt="background colors" width="276" height="449" /></p><p><strong>Figure 5 Blocks of Content with Background Colors</strong></p><p>In the second example, a media query applies styles defined for screen sizes greater than 481 pixels—anything wider than a typical smartphone. You can use the Grid to define two columns and move the blocks into desired positions, as below. The results are shown in <strong>Figure 6</strong>.</p><pre>@media only screen and (min-width : 481px) {
/*make two columns and move block 3 next to 1 — just because we can*/
    #mygrid {
        display: -ms-grid;
        -ms-grid-columns: 10px 1fr 10px 1fr 10px; /*10px columns to spacing in between*/
        -ms-grid-rows: 100px 1fr 1fr; /*100px row and two rows each taking 1 fraction of available space*/
        margin: 5px;
    }
    #myheader {
        -ms-grid-row: 1;
        -ms-grid-column: 1;
        -ms-grid-column-span: 5;
        background-color: #EEB215;
    }
    #block1 {
        -ms-grid-row: 2;
        -ms-grid-column: 2;
        background-color: #B2B0B0;
    }
    #block2 {
        -ms-grid-row: 3;
        -ms-grid-column: 2;
        background-color: #726E6E;
    }
    #block3 {
        -ms-grid-row: 2; /*block 3 can go into row 2*/
        -ms-grid-column: 4;
         background-color: #515050;
    }
}</pre><p><img
class="alignnone size-full wp-image-50792" title="figure6" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/figure61.png" alt="two adjacent columns" width="550" height="434" /><br
/> <strong>Figure 6 A New Layout with Two Adjacent Columns</strong></p><p>The third grid sample displays on screen widths greater than 1220 pixels. You define a grid with a wide header that spans multiple columns and then define three columns, each occupying one fraction of the available space, with a few 10-pixel columns in between. The results are shown in <strong>Figure 7</strong>.</p><pre>@media only screen and (min-width: 1220px) {
    #mygrid {
        display: -ms-grid;
        -ms-grid-columns: 1fr 10px 1fr 10px 1fr;
        -ms-grid-rows: 100px 1fr;
        margin: 5px;
    }
    #myheader {
        -ms-grid-row: 1;
        -ms-grid-column: 1;
        -ms-grid-column-span: 5;
        background-color: #EEB215;
    }
    #block1 {
        -ms-grid-row: 2;
        -ms-grid-column: 1;
        background-color: #B2B0B0;
    }
    #block2 {
        -ms-grid-row: 2;
        -ms-grid-column: 3;
        background-color: #726E6E;
    }
    #block3 {
        -ms-grid-row: 2;
        -ms-grid-column: 5;
        background-color: #515050;
    }
}</pre><p>&nbsp;<br
/> <img
class="alignnone size-full wp-image-50793" title="figure7" src="http://cdn.sitepoint.com/wp-content/uploads/2012/01/figure71.png" alt="three columns" width="551" height="187" /><br
/> <strong>Figure 7 Three Side-by-Side Columns with a Spanning Header</strong></p><p>The Grid specification is a welcome addition for implementing responsive web designs.</p><p>Two other new CSS specifications are also worth mentioning: the <a
href="http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/">Flexible Box Layout Module</a> (Flexbox) and The <a
href="http://www.w3.org/TR/css3-multicol/">Multi-column Layout Module</a>. Both show a great deal of promise for designing responsive Websites.</p><p>Flexbox, currently a working draft at the W3C, adds support for four new layout modes: block, inline, table, and positioned. It enables you to lay out complex pages with relative position and constant size, even when screen sizes change.</p><p>The multi-column layout module is currently a candidate recommendation at the W3C. This solution is for content that you need to lay out in columns and that flow from one column into the next. You can view an interactive example of multi-column layout in this <a
href="http://ie.microsoft.com/testdrive/Graphics/hands-on-css3/hands-on_multi-column.htm">lab</a>.</p><h3>Flexible Images and Media</h3><p>The final aspect of responsive web design is flexible images and media. Basically, this feature allows you to adapt your images or other media to load differently depending on the device, either by scaling or by using the CSS overflow property.</p><p>Scaling in CSS is pretty simple to implement for both images and video. You can set the media element’s max-width to 100 percent, and the browser will make the image shrink and expand depending on its container. You should supply the image in the best quality and size possible and then let CSS adapt the image to the right size.</p><pre>img, object {
    max-width: 100%;
}</pre><p>&nbsp;</p><p>An alternative to scaling images is cropping them with CSS. For example, applying overflow:hidden allows you to crop images dynamically so that they fit into their containers as the containers resize to fit a new screen environment.</p><p>Having several options to scale and crop images in CSS might not be enough. Do you really need to take up all of a visitor’s mobile bandwidth because you don’t have a smaller version of an image? To better serve users, flexible images might mean using an alternative image—or even no image at all. Folks in the web design community are coming up with <a
href="http://filamentgroup.com/lab/responsive_images_experimenting_with_context_aware_image_sizing/">solutions</a> based on JavaScript and cookies, and you can expect more of this as responsive web design evolves and becomes the basis for many quality Websites.</p><h3>Legacy Browsers</h3><p>What about older browsers that don’t support media queries? What about Internet Explorer before version 8, which has issues with scaling images? Solutions in the form of polyfills can help. Here are some useful examples.</p><ul><li>css3-mediaqueries.js by Wouter van der Graaf: <a
href="http://msdn.microsoft.com/en-us/magazine/code.google.com/p/css3-mediaqueries-js/">code.google.com/p/css3-mediaqueries-js/</a></li><li>Response.js: <a
href="http://msdn.microsoft.com/en-us/magazine/github.com/scottjehl/Respond">github.com/scottjehl/Respond</a></li><li>Fluid images: <a
href="http://msdn.microsoft.com/en-us/magazine/unstoppablerobotninja.com/entry/fluid-images/">unstoppablerobotninja.com/entry/fluid-images/</a></li></ul><h3>In Closing</h3><p>Jumping on the responsive web design wagon isn’t something to take lightly. Take into account what you need to achieve, and consider whether catering to a specific version of a desktop or mobile device makes the most sense.</p><p>Responsive web design is in its early stages. Web designers will continue to offer different opinions and recommend directions related to whether to build for mobile first, how to fit these decisions into the design process, whether to slice up the comps into all the different screen sizes, and so forth. And as more and more screen sizes and form factors arrive, the conversation will continue.</p><p>HTML and CSS standards are evolving to help web designers deal with these issues. It’s clear that some form of responsive web design will be used to meet the challenges, and it’s equally clear that standards will continue to evolve as better ways of handling the changing world of devices and browsers are discovered.</p><p>Here are some additional resources:</p><ul><li><a
href="http://www.alistapart.com/articles/responsive-web-design/">Responsive Web Design</a></li><li><a
href="http://www.smashingmagazine.com/2011/07/22/responsive-web-design-techniques-tools-and-design-strategies/">Responsive Web Design Techniques, Tools and Design Strategies</a></li><li><a
href="http://stuffandnonsense.co.uk/blog/about/hardboiled_css3_media_queries">Hardboiled CSS3 Media Queries</a></li><li><a
href="http://goldengridsystem.com/">Golden Grid System</a></li><li><a
title="Permanent Link to A Brief Look at Grid-Based Layouts in Web Design" href="http://sixrevisions.com/web_design/a-brief-look-at-grid-based-layouts-in-web-design/">A Brief Look at Grid-Based Layouts in Web Design</a></li></ul><div
style="text-align:center;padding-bottom:50px;"><div
style="float:left;padding-left:30px;"> <script>GA_googleFillSlot("Edit_300x100_C");</script> </div><div
style="float:right;padding-right:30px;"> <script>GA_googleFillSlot("Edit_300x100_D");</script> </div></div><div
style="clear:both"></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/responsive-web-design/feed/</wfw:commentRss> <slash:comments>11</slash:comments> </item> <item><title>Managing Multiple Sites with WordPress Network</title><link>http://www.sitepoint.com/managing-multiple-sites-with-wordpress-network/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=managing-multiple-sites-with-wordpress-network</link> <comments>http://www.sitepoint.com/managing-multiple-sites-with-wordpress-network/#comments</comments> <pubDate>Thu, 26 Jan 2012 04:27:26 +0000</pubDate> <dc:creator>Daniel Shamburger</dc:creator> <category><![CDATA[Web Tech]]></category> <category><![CDATA[wordpress]]></category> <category><![CDATA[WordPress]]></category> <category><![CDATA[WordPress Network]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=50752</guid> <description><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2010/11/wordpress-logo-115x115.jpg" class="attachment-thumbnail wp-post-image" alt="wordpress-logo-115x115" title="wordpress-logo-115x115" />Managing and updating software for multiple WordPress sites can be a real hassle. Daniel Shamburger finds WordPress Network makes it much easier.]]></description> <content:encoded><![CDATA[<img
width="50" height="50" src="http://cdn.sitepoint.com/wp-content/uploads/2010/11/wordpress-logo-115x115.jpg" class="attachment-thumbnail wp-post-image" alt="wordpress-logo-115x115" title="wordpress-logo-115x115" /><p></p><p>Here you are, a web developer currently working on several different WordPress sites at varying stages of development. They&#8217;re all in different directories on your domain so clients can have a look and see how they&#8217;re coming along. Out of nowhere, a major new WordPress version is released, and the Genesis framework you&#8217;re using to build all your sites needs to be updated.</p><p>Managing all your WordPress installations at a times like this can be a real hassle. This may not be your exact story, but I&#8217;m sure many of you can sympathize.</p><p>WordPress Network comes to the rescue in situations like this. Once you&#8217;ve set it up, you can put multiple sites in directories and subdomains with the click of a button. Since they all share the same WP installation you can update and edit them all in one fell swoop from your Network Admin dashboard.</p><p>Before you start, unless this is a brand new WordPress installation with nothing to lose, you&#8217;ll probably want to back up your database and files. You also need to disable any active plugins. You can start them back up after the network setup is complete.<div>  <script type='text/javascript'>GA_googleFillSlot("InArticle_728x90_1");</script> </div></p><p>Now for the nuts and bolts of creating a new WordPress Network.</p><p>First you&#8217;ll need to enable Multisite. Use your FTP client or web server&#8217;s file browser and download a file called <code>wp-config.php</code> and save it to your desktop or a folder. Open it with your text editor and add this line above where it says <code>"/* That's all, stop editing! Happy blogging. */"</code>.</p><pre>define('WP_ALLOW_MULTISITE', true);</pre><p>Save the file and upload it back to the server. Since the original <code>wp-config.php</code> is still there, it will ask you which file you want to keep. Choose &#8220;replace&#8221; or &#8220;overwrite&#8221; to save the newer, edited version.</p><p>You&#8217;ll need to refresh your admin panel in your browser to let these changes take effect.</p><p>In your <strong>Tools</strong> menu in the left sidebar, you&#8217;ll now see the <strong>Network Setup</strong> item. Click on that and then go to <strong>Create a Network of WordPress Sites</strong>. Follow the directions and choose a few options such as the URL structure and network name.</p><p>You&#8217;ll then be prompted to make a <code>blogs.dir</code> directory in <code>/wp-content</code> and it will provide several more lines of code to add to the <code>wp-config.php</code> file.</p><p>It will also tell you to add some rules to <code>.htaccess</code>, a server text file used to work with permissions and configurations for each directory.</p><p>Use your FTP program of choice to download this file. You may need to tell your FTP program not to hide this file, which you should be able to specify in the program&#8217;s options or preferences.</p><p>Even when you have downloaded the file, you may find your operating system&#8217;s file manager hides the file from you, so here are some directions for how to show it.</p><h4>Mac</h4><p>Open <strong>Terminal</strong>, found in <strong>Applications/Utilities</strong>.</p><p>Type/paste in this and hit return/enter:</p><pre>defaults write com.apple.finder AppleShowAllFiles -bool true</pre><p>Finder must be restarted to allow this to take effect. In Terminal paste in this and hit enter:</p><pre>killall Finder</pre><p>When you&#8217;re done, if you&#8217;d like to hide hidden files again, use the same line as used to hide it, but change &#8220;true&#8221; at the end to &#8220;false&#8221; and restart Finder.</p><h4>Windows</h4><p>Press the <strong>Start</strong> menu. Click on <strong>Control Panel</strong>, <strong>Appearance and Personalization</strong>, and then <strong>Folder Options</strong>. Go to the <strong>View</strong> tab. Under <strong>Advanced Settings</strong>, select &#8220;<em>Show hidden files and folders</em>&#8221; and hit &#8220;<em>OK</em>&#8220;.</p><p>Once you have shown hidden files, open <code>.htaccess</code> and add the code given by WordPress Network Setup, save the file and re-upload it.</p><p>It is possible that this file has not already been placed on your website. If, after setting your FTP program to display hidden files, you still don&#8217;t see the <code>.htaccess</code> file in your website&#8217;s root public directory, you&#8217;ll need to create a new one.</p><p>Create a new file in your text editor, paste in the code given by WordPress Network Setup, save that as <code>.htaccess</code> to your desktop or a folder, and upload it to the server, in the root public directory of your website.</p><p>When you log into the <strong>Network Admin</strong>, you&#8217;ll now see a &#8220;My Sites&#8221; item. Hover over that, and under &#8220;Network Admin&#8221;, there will be several administration items. When you click on &#8220;Sites&#8221;, you can add new sites with the click of a button!</p><p>Back under the main &#8220;My Sites&#8221; menu, you can manage all the network sites.</p><p>Setup is complete!</p><p>Now, with your WordPress network, updating and making changes to all your sites is simple and far less time-consuming.</p><div
style="text-align:center;padding-bottom:50px;"><div
style="float:left;padding-left:30px;"> <script>GA_googleFillSlot("Edit_300x100_C");</script> </div><div
style="float:right;padding-right:30px;"> <script>GA_googleFillSlot("Edit_300x100_D");</script> </div></div><div
style="clear:both"></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/managing-multiple-sites-with-wordpress-network/feed/</wfw:commentRss> <slash:comments>14</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using memcached
Database Caching 47/138 queries in 0.117 seconds using memcached
Object Caching 2944/3151 objects using memcached
Content Delivery Network via cdn.sitepoint.com

Served from: www.sitepoint.com @ 2012-02-09 22:38:33 -->
