<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>The CSS Ninja</title>
	
	<link>http://www.thecssninja.com</link>
	<description>All things CSS, JavaScript &amp; HTML</description>
	<lastBuildDate>Fri, 27 Apr 2012 00:42:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/TheCSSNinja" /><feedburner:info uri="thecssninja" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Testing on Mobile devices</title>
		<link>http://feedproxy.google.com/~r/TheCSSNinja/~3/D01MftNjeoo/testing-devices</link>
		<comments>http://www.thecssninja.com/mobile/testing-devices#comments</comments>
		<pubDate>Wed, 28 Mar 2012 08:58:41 +0000</pubDate>
		<dc:creator>Ryan Seddon</dc:creator>
				<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://www.thecssninja.com/?p=1026</guid>
		<description><![CDATA[A while back Brad Frost posted a very useful breakdown on testing mobile devices and how to do it without breaking the bank. This post is kind of an extension to it but pointing to other useful resources that I have come across and used. Frost went down the route of physical devices, what you [...]]]></description>
			<content:encoded><![CDATA[<p>A while back Brad Frost posted a very useful breakdown on <a href="http://bradfrostweb.com/blog/mobile/test-on-real-mobile-devices-without-breaking-the-bank/">testing mobile devices</a> and how to do it without breaking the bank. This post is kind of an extension to it but pointing to other useful resources that I have come across and used.</p>
<p>Frost went down the route of physical devices, what you should test and their breakdown in prices. This post will be a list of services I have come across for testing on a vast array mobile devices without having to purchase said devices.<span id="more-1026"></span></p>
<h2 class="subtitle02">DeviceAnywhere</h2>
<p>DeviceAnywhere <a href="http://www.keynotedeviceanywhere.com/mobile-application-testing.html">Test Center</a> is a device lab chock full of common and not so common devices that you can access remotely though their application. It gives you remote access to real devices, not emulators, and the ability to do almost anything to them. In my case I would only access the browser apps on each phone but you have full access to the phone and its capabilities.</p>
<h2 class="subtitle02">Pros:</h2>
<ul>
<li>Record video and image capture</li>
<li>Invite other users to a watch or participate in testing</li>
<li>Huge amount of <a href="http://www.keynotedeviceanywhere.com/test-center-device-list.html ">devices</a> including tablets.</li>
<li>Good support for emulating touch and gestures.</li>
<li>Relatively <a href="http://www.keynotedeviceanywhere.com/test-center-pricing.html">cheap</a>.</li>
</ul>
<h2 class="subtitle02">Cons:</h2>
<ul>
<li>Laggy and not super responsive (Latency from Australia most likely faster in USA and UK).</li>
<li>Automation and scripting is part of their enterprise product which is very pricey.</li>
</ul>
<p><strong>Price:</strong> ~$16USD/hr for general access to the device lab. Packages and bulk hours equals cheaper prices.</p>
<h2 class="subtitle02">Perfecto Mobile</h2>
<p>PerfectoMobile <a href="http://www.perfectomobile.com/portal/cms/services/overview.html">MobileCloud</a> is very similar to DeviceAnywhere both offer a huge array of real devices you can remotely access. PerfectoMobile uses a flash based web app for accessing and testing on devices.</p>
<h2 class="subtitle02">Pros:</h2>
<ul>
<li>Record video and image capture</li>
<li>Invite other users to a watch or participate in testing</li>
<li>Huge amount of <a href="http://www.perfectomobile.com/portal/cms/services/handsets.html">devices</a> including tablets.</li>
<li>Have dedicated handset options: <a href="http://www.perfectomobile.com/portal/cms/services/blackberry.html">Blackberry</a> and <a href="http://www.perfectomobile.com/portal/cms/services/nokia.html">Nokia</a></li>
</ul>
<h2 class="subtitle02">Cons:</h2>
<ul>
<li>Laggy and not super responsive (Latency from Australia most likely faster in USA and UK).</li>
<li>Automation and scripting is part of their enterprise product which is very pricey.</li>
<li>Touch and gestures aren&#8217;t that easy to accomplish.</li>
<li><a href="http://www.perfectomobile.com/portal/cms/pricing/">Pricey</a>, even for entry level access.</li>
</ul>
<p><strong>Price:</strong> ~$170USD/10hrs per month. Blackberry $4USD/hr, Nokia $14USD/hr.</p>
<h2 class="subtitle02">BrowserStack</h2>
<p><a href="http://www.browserstack.com/mobile-browser-emulator">BrowserStack</a> recently launched remote access to an array of Mobile and tablet emulators with real device configurations. All in browser access.</p>
<h2 class="subtitle02">Pros:</h2>
<ul>
<li>Good cheap <a href="http://www.browserstack.com/pricing">pricing</a></li>
<li>Can test localhost remotely<sup>1</sup></li>
<li>Automation! BrowserStack has an <a href="http://www.browserstack.com/automated-browser-testing-api">API</a> for spinning up an emulator and scripting interaction. Huge.</li>
</ul>
<h2 class="subtitle02">Cons:</h2>
<ul>
<li>Not real devices, but when it&#8217;s for browser testing that&#8217;s less of an issue.</li>
<li>Smaller, but growing, <a href="http://www.browserstack.com/mobile-browser-emulator#list">list of mobile browsers</a>. But really they cover 99% of the most used ones already.</li>
</ul>
<p><strong>Price:</strong> $19USD/Month for an individual. Gives you access to Mobile and desktop browsers.</p>
<p><sup>1</sup> Note: BrowserStack provides their own implementation of a localtunnel like service. You can of course use localtunnel or similar on your own machine for testing your localhost with other services. </p>
<h2 class="subtitle02">Nokia Remote Device Access</h2>
<p><a href="http://apu.ndhub.net/">Nokia RDA</a> is a device lab of, you guessed it, Nokia devices where you can remotely access an array of Nokia phones.</p>
<h2 class="subtitle02">Pros:</h2>
<ul>
<li>It&#8217;s free! You just need to sign up for Nokia dev account.</li>
<li>Huge list of <a href="http://apu.ndhub.net/devices">Nokia phones</a> available.</li>
<li>Record and screen capture.</li>
<li>Pretty responsive.</li>
</ul>
<h2 class="subtitle02">Cons:</h2>
<ul>
<li>Pretty lame con but it&#8217;s free and therefore could disappear.</li>
</ul>
<p><strong>Price:</strong> FREE!</p>
<p>So that&#8217;s it. If you know of any other services that I may have missed let me know. I think a combination of real devices and remote access is the killer setup for any mobile development shop or individual.</p>
<p class="shorty01">Short URL: <a href="http://cssn.in/ja/040">http://cssn.in/ja/040</a></p>
<div class="clear">&nbsp;</div>
]]></content:encoded>
			<wfw:commentRss>http://www.thecssninja.com/mobile/testing-devices/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.thecssninja.com/mobile/testing-devices</feedburner:origLink></item>
		<item>
		<title>Introduction to JavaScript Source Maps</title>
		<link>http://feedproxy.google.com/~r/TheCSSNinja/~3/e4P1Ztag-6s/source-mapping</link>
		<comments>http://www.thecssninja.com/javascript/source-mapping#comments</comments>
		<pubDate>Wed, 21 Mar 2012 23:55:26 +0000</pubDate>
		<dc:creator>Ryan Seddon</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.thecssninja.com/?p=982</guid>
		<description><![CDATA[Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you&#8217;ve combined and minified it, without impacting performance? Well now you can through the magic of source maps. Basically it&#8217;s a way to map a combined/minified file back to an unbuilt state. When you build for [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you&#8217;ve combined and minified it, without impacting performance? Well now you can through the magic of <a href="https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?hl=en_US&amp;pli=1&amp;pli=1">source maps</a>.</p>
<p><span id="more-982"></span></p>
<p>Basically it&#8217;s a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, or Google Chrome Canary) can parse the source map automatically and make it appear as though you&#8217;re running unminified and uncombined files. As of writing Firefox has a blocked status for Source Map support. See <a href="https://wiki.mozilla.org/DevTools/Features/SourceMap">MozillaWiki Source Map</a> entry for more details.</p>
<div class="resources01"><a href="http://www.thecssninja.com/demo/source_mapping/" target="_blank" title="Source mapping demo" class="demo">View a live demo</a> <a href="http://www.thecssninja.com/demo/source_mapping/source_mapping.zip" title="Download the source of the source mapping demo" class="demo source">Download the source files</a></div>
<p>The above demo allows you to right click anywhere in the textarea containing the generated source. Select &#8220;Get original location&#8221; will query the source map by passing in the generated line and column number, and return the position in the original code. Make sure your console is open so you can see the output.</p>
<p><img src="http://www.thecssninja.com/wp-content/uploads/2012/03/source-map-demo.png" alt="Source map demo screenshot" title="Example of the Mozilla JavaScript source map library in action" width="609" height="155" class="article-img main-img" /></p>
<h2 class="subtitle02">Real world</h2>
<p>Before you view the following real world implementation of Source Maps make sure you&#8217;ve enabled the source maps feature in either Chrome Canary or WebKit nightly by clicking the settings cog in the dev tools panel and checking the &#8220;Enable source maps&#8221; option. See screenshot below.</p>
<p><img src="http://www.thecssninja.com/wp-content/uploads/2012/03/enable-source-maps.png" alt="" title="How to enable source maps in WebKit dev tools" width="609" height="232" class="article-img main-img" /></p>
<p>So&#8230; That Source Map query demo is cool and all but what about a real world use case? Take a look at the special build of font dragr at <a href="http://dev.fontdragr.com/">dev.fontdragr.com</a> in Chrome Canary or WebKit nightly, with source mapping enabled, and you&#8217;ll notice that the JavaScript isn&#8217;t compiled and you can see all the individual JavaScript files it references. This is using source mapping, but behind the scenes actually running the compiled code. Any errors, logs and breakpoints will map to the dev code for awesome debugging! So in effect it gives you the illusion that you&#8217;re running a dev site in production.</p>
<h2 class="subtitle02">Why should I care about source maps?</h2>
<p>Right now source mapping is only working between uncompressed/combined JavaScript to compressed/uncombined JavaScript, but the future is looking bright with talks of compiled-to-JavaScript languages such as CoffeeScript and even the possibility of adding support for CSS preprocessors like SASS or LESS.</p>
<p>In the future we could easily use almost any language as though it were supported natively in the browser with source maps:</p>
<ul>
<li>CoffeeScript</li>
<li>ECMAScript 6 and beyond</li>
<li>SASS/LESS and others</li>
<li>Pretty much any language that compiles to JavaScript</li>
</ul>
<p>Take a look at this screencast of CoffeeScript being debugged in an experimental build of the Firefox console:</p>
<p><iframe width="609" height="339" src="http://www.youtube.com/embed/2aQw1dSIYko?start=625" frameborder="0" allowfullscreen></iframe></p>
<p>The Google Web Toolkit (GWT) has recently added <a href="http://code.google.com/p/google-web-toolkit/wiki/SourceMaps">support for Source Maps</a> and Ray Cromwell of the GWT team did an awesome screencast showing source map support in action.</p>
<p><iframe width="609" height="339" src="http://www.youtube.com/embed/-xJl22Kvgjg" frameborder="0" allowfullscreen></iframe></p>
<p>Another example I&#8217;ve put together uses Google&#8217;s <a href="http://code.google.com/p/traceur-compiler/">Traceur</a> library which allows you to write ES6 (ECMAScript 6 or Next) and compile it to ES3 compatible code. The Traceur compiler also generates a source map. Take a look at this <a href="http://www.thecssninja.com/demo/source_mapping/ES6/">demo</a> of ES6 traits and classes being used like they&#8217;re supported natively in the browser, thanks to the source map. The textarea in the demo also allows you to write ES6 which will be compiled on the fly and generate a source map plus the equivalent ES3 code.</p>
<p><img src="http://www.thecssninja.com/wp-content/uploads/2012/03/source-map-es6.png" alt="" title="Traceur ES6 debugging using source maps" width="609" height="263" class="article-img main-img" /></p>
<h2 class="subtitle02">How does the source map work?</h2>
<p>The only JavaScript compiler/minifier that has support, at the moment, for source map generation is the Closure compiler. (I&#8217;ll explain how to use it later.) Once you&#8217;ve combined and minified your JavaScript, alongside it will exist a sourcemap file. Currently, the Closure compiler doesn&#8217;t add the special comment at the end that is required to signify to WebKit and Chrome Canary dev tools that a source map is available:</p>
<div class="code syntax">
<pre>//@ sourceMappingURL=/path/to/file.js.map</pre>
</div>
<p>This enables developer tools to map calls back to their location in original source files. If you don&#8217;t like the idea of the weird comment you can alternatively set a special header on your compiled JavaScript file:</p>
<div class="code syntax">
<pre>X-SourceMap: /path/to/file.js.map</pre>
</div>
<p>Like the comment this will tell your source map consumer where to look for the source map associated with a JavaScript file. This header also gets around the issue of referencing source maps in languages that don&#8217;t support single-line comments.</p>
<p><img src="http://www.thecssninja.com/wp-content/uploads/2012/03/sourcemap-on-off.png" alt="WebKit Devtools example of source maps on and source maps off" title="Showing dev tools when source map in off and when it&#039;s on." width="609" height="160" class="article-img main-img" /></p>
<p>The source map file will only be downloaded if you have source maps enabled and your dev tools open. You&#8217;ll also need to upload your original files so the dev tools can reference and display them when necessary.</p>
<h2 class="subtitle02">How do I generate a source map?</h2>
<p>Like I mentioned above you&#8217;ll need to use the <a href="https://developers.google.com/closure/compiler/">Closure compiler</a> to minify, concat and generate a source map for your JavaScript files. The command is as follows:</p>
<div class="code syntax">
<pre>java -jar compiler.jar <span class="se">\ </span>
     --js script.js <span class="se">\</span>
     --create_source_map ./script-min.js.map <span class="se">\</span>
     --source_map_format<span class="o">=</span>V3 <span class="se">\</span>
     --js_output_file script-min.js
</pre>
</div>
<p>The two important command flags are <code>--create_source_map</code> and <code>--source_map_format</code>. This is required as the default version is V2 and we only want to work with V3.</p>
<h2 class="subtitle02">The anatomy of a source map</h2>
<p>In order to better understand a source map we&#8217;ll take a small example of a source map file that would be generated by the Closure compiler and dive into more detail on how the &#8220;mappings&#8221; section works. The following example is a slight variation from the <a href="https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?hl=en_US&amp;pli=1&amp;pli=1">V3 spec</a> example.</p>
<div class="code syntax">
<pre><span class="p">{</span>
    <span class="nx">version</span> <span class="o">:</span> <span class="mi">3</span><span class="p">,</span>
    <span class="nx">file</span><span class="o">:</span> <span class="s2">"out.js"</span><span class="p">,</span>
    <span class="nx">sourceRoot</span> <span class="o">:</span> <span class="s2">""</span><span class="p">,</span>
    <span class="nx">sources</span><span class="o">:</span> <span class="p">[</span><span class="s2">"foo.js"</span><span class="p">,</span> <span class="s2">"bar.js"</span><span class="p">],</span>
    <span class="nx">names</span><span class="o">:</span> <span class="p">[</span><span class="s2">"src"</span><span class="p">,</span> <span class="s2">"maps"</span><span class="p">,</span> <span class="s2">"are"</span><span class="p">,</span> <span class="s2">"fun"</span><span class="p">],</span>
    <span class="nx">mappings</span><span class="o">:</span> <span class="s2">"AAgBC,SAAQ,CAAEA"</span>
<span class="p">}</span>
</pre>
</div>
<p>Above you can see that a source map is an object literal containing lots of juicy info:</p>
<ul>
<li>Version number that the source map is based off</li>
<li>The file name of the generated code (Your minifed/combined production file)</li>
<li>sourceRoot allows you to prepend the sources with a folder structure &ndash; this is also a space saving technique</li>
<li>sources contains all the file names that were combined</li>
<li>names contains all variable/method names that appear throughout your code.</li>
<li>Lastly the mappings property is where the magic happens using Base64 VLQ values. The real space saving is done here.</li>
</ul>
<h2 class="subtitle02">Base64 VLQ and keeping the source map small</h2>
<p>Originally the source map spec had a very verbose output of all the mappings and resulted in the sourcemap being about 10 times the size of the generated code. Version two reduced that by around 50% and version three reduced it again by another 50%, so for a 133kB file you end up with a ~300kB source map. So how did they reduce the size while still maintaining the complex mappings?</p>
<p><a href="http://en.wikipedia.org/wiki/Variable-length_quantity">VLQ</a> (Variable Length Quantity) is used along with encoding the value into a Base64 value. The mappings property is a super big string. Within this string are semicolons (;) that represent a line number within the generated file. Within each line there are commas (,) that represent each segment within that line. Each of these segments is either 1, 4 or 5 in variable length fields. Some may appear longer but these contain continuation bits. Each segment builds upon the previous, which helps reduce the file size as each bit is relative to its previous segments.</p>
<p><img src="http://www.thecssninja.com/wp-content/uploads/2012/03/source-map-segment.png" alt="" title="Break down of a segment within the source map JSON file" width="609" height="300" class="article-img main-img" /></p>
<p>Like I mentioned above each segment can be 1, 4 or 5 in variable length. This diagram is considered a variable length of four with one continuation bit (g). We&#8217;ll break down this segment and show you how the source map works out the original location. The values shown above are purely the Base64 decoded values, there is some more processing to get their true values. Each segment usually works out five things:</p>
<ul>
<li>Generated column</li>
<li>Original file this appeared in</li>
<li>Original line number</li>
<li>Original column </li>
<li>And if available original name. </li>
</ul>
<p>Not every segment has a name, method name or argument, so segments throughout will switch between four and five variable length. The g value in the segment diagram above is what&#8217;s called a continuation bit this allows for further optimisation in the Base64 VLQ decoding stage. A continuation bit allows you to build on a segment value so you can store big numbers without having to store a big number, a very clever space saving technique that has its roots in the midi format.</p>
<p>The above diagram <code>AAgBC</code> once processed further would return 0, 0, 32, 16, 1 &ndash; the 32 being the continuation bit that helps build the following value of 16. B purely decoded in Base64 is 1. So the important values that are used are 0, 0, 16, 1. This then lets us know that line 1 (lines are kept count by the semi colons) column 0 of the generated file maps to file 0 (array of files 0 is foo.js), line 16 at column 1.</p>
<p>To show how the segments get decoded I will be referencing Mozilla&#8217;s <a href="https://github.com/mozilla/source-map/">Source Map JavaScript library</a>. You can also look at the WebKit dev tools <a href="http://code.google.com/codesearch#OAMlx_jo-ck/src/third_party/WebKit/Source/WebCore/inspector/front-end/CompilerSourceMapping.js">source mapping code</a>, also written in JavaScript.</p>
<p>In order to properly understand how we get the value 16 from B we need to have a basic understanding of bitwise operators and how the spec works for source mapping. The preceding digit, g, gets flagged as a continuation bit by comparing the digit (32) and the <a href="https://github.com/mozilla/source-map/blob/master/lib/source-map/base64-vlq.js#L32">VLQ_CONTINUATION_BIT</a> (binary 100000 or 32) by using the bitwise AND (&amp;) operator.</p>
<div class="code syntax">
<pre>32 &amp; 32 = 32
// or
100000
|
|
V
100000</pre>
</div>
<p>This returns a 1 in each bit position where both have it appear. So a Base64 decoded value of <code>33 &#038; 32</code> would return 32 as they only share the 32 bit location as you can see in the above diagram. This then increases the the bit <a href="https://github.com/mozilla/source-map/blob/master/lib/source-map/base64-vlq.js#L52">shift value</a> by 5 for each preceding continuation bit. In the above case its only shifted by 5 once, so left shifting 1 (B) by 5.</p>
<div class="code syntax">
<pre>1 &lt;&lt; 5 // 32

// Shift the bit by 5 spots
______
|    |
V    V
100001 = 100000 = 32</pre>
</div>
<p>That value is then converted from a VLQ signed value by right shifting the number (32) one spot.</p>
<div class="code syntax">
<pre>32 >> 1 // 16
//or
100000
|
 |
 V
010000 = 16</pre>
</div>
<p>So there we have it: that is how you turn 1 into 16. This may seem an over complicated process, but once the numbers start getting bigger it makes more sense.</p>
<h2 class="subtitle02">Potential XSSI issues</h2>
<p>The spec mentions cross site script inclusion issues that could arise from the consumption of a source map. To mitigate this it&#8217;s recommended that you prepend the first line of your source map with &#8220;<code>)]}</code>&#8221; to deliberately invalidate JavaScript so a syntax error will be thrown. The WebKit dev tools can handle this already.</p>
<div class="code syntax">
<pre><span class="k">if</span> <span class="p">(</span><span class="nx">response</span><span class="p">.</span><span class="nx">slice</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="o">===</span> <span class="s2">")]}"</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">response</span> <span class="o">=</span> <span class="nx">response</span><span class="p">.</span><span class="nx">substring</span><span class="p">(</span><span class="nx">response</span><span class="p">.</span><span class="nx">indexOf</span><span class="p">(</span><span class="s1">'\n'</span><span class="p">));</span>
<span class="p">}</span>
</pre>
</div>
<p>As shown above, the first three characters are sliced to check if they match the syntax error in the spec and if so removes all characters leading up to the first new line entity (\n).</p>
<h2 class="subtitle02">@sourceURL and displayName in action: Eval and anonymous functions</h2>
<p>While not part of the source map spec the following two conventions allow you to make development much easier when working with evals and anonymous functions.</p>
<p>The first helper looks very similar to the <code>//@ sourceMappingURL</code> property and is actually mentioned in the source map V3 spec. By including the following special comment in your code, which will be evaled, you can name evals so they appear as more logical names in your dev tools. Check out a <a href="http://www.thecssninja.com/demo/source_mapping/compile.html">simple demo</a> using the CoffeeScript compiler.</p>
<div class="code syntax">
<pre>//@ sourceURL=sqrt.coffee</pre>
</div>
<p><img src="http://www.thecssninja.com/wp-content/uploads/2012/03/source-url.png" alt="" title="What sourceURL special comment looks like in dev tools" width="609" height="195" class="article-img main-img" /></p>
<p>The other helper allows you to name anonymous functions by using the <code>displayName</code> property available on the current context of the anonymous function. Profile the <a href="http://www.thecssninja.com/demo/source_mapping/displayName.html">following demo</a> to see the <code>displayName</code> property in action.</p>
<div class="code syntax">
<pre><span class="nx">btns</span><span class="p">[</span><span class="mi">0</span><span class="p">].</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s2">"click"</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">fn</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
        <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">"You clicked button number: 1"</span><span class="p">);</span>
    <span class="p">};</span>

    <span class="nx">fn</span><span class="p">.</span><span class="nx">displayName</span> <span class="o">=</span> <span class="s2">"Anonymous function of button 1"</span><span class="p">;</span>

    <span class="k">return</span> <span class="nx">fn</span><span class="p">();</span>
<span class="p">},</span> <span class="kc">false</span><span class="p">);</span>
</pre>
</div>
<p><img src="http://www.thecssninja.com/wp-content/uploads/2012/03/display-name.png" alt="" title="Example showing the displayName property in action" width="611" height="149" class="article-img main-img" /></p>
<p>When profiling your code within the dev tools the <code>displayName</code> property will be shown rather than something like <code>(anonymous)</code>. However displayName is pretty much dead in the water and won&#8217;t be making it into Chrome. But all hope isn&#8217;t lost and a much better proposal has been suggested called <a href="http://code.google.com/p/chromium/issues/detail?id=116220">debugName</a>.</p>
<p>As of writing the eval naming is only available in Firefox and WebKit browsers. The <code>displayName</code> property is only in WebKit nightlies.</p>
<h2 class="subtitle01">Let&#8217;s rally together</h2>
<p>Currently there is very lengthy discussion on <a href="https://github.com/jashkenas/coffee-script/issues/558">source map support</a> being added to CoffeeScript. Go check out the issue and add your support for getting source map generation added to the CoffeeScript compiler. This will be a huge win for CoffeeScript and its devoted followers.</p>
<p>UglifyJS also has a <a href="https://github.com/mishoo/UglifyJS/issues/315">source map issue</a> you should take a look at too.</p>
<p>The more tools available to us that can generate a source maps the better off we&#8217;ll be, so go forth and ask or add source map support to your favourite open source project.</p>
<h2 class="subtitle02">It&#8217;s not perfect</h2>
<p>One thing Source Maps doesn&#8217;t cater for right now is watch expressions. The problem is that trying to inspect an argument or variable name within the current execution context won&#8217;t return anything as it doesn&#8217;t really exist. This would require some sort of reverse mapping to lookup the real name of the argument/variable you wish to inspect compared to the actual argument/variable name in your compiled JavaScript.</p>
<p>This of course is a solvable problem and with more attention on source maps we can start seeing some amazing features and better stability.</p>
<h2 class="subtitle02">Tools and resource</h2>
<p>Here&#8217;s some further resources and tools you should check out:</p>
<ul>
<li>Nick Fitzgerald has a fork of <a href="https://github.com/fitzgen/UglifyJS/tree/source-maps">UglifyJS</a> with source map support</li>
<li>Paul Irish has a handy little <a href="http://dl.dropbox.com/u/39519/sourcemapapp/index.html">demo</a> showing off source maps</li>
<li>Check out the WebKit changeset of when this <a href="http://trac.webkit.org/changeset/103541">dropped</a></li>
<li>The changeset also included a <a href="http://trac.webkit.org/export/105549/trunk/LayoutTests/http/tests/inspector/compiler-source-mapping-debug.html">layout test</a> which got this whole article started</li>
<li>Mozilla has a <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=670002">bug</a> you should follow on the status of source maps in the built-in console</li>
<li>Conrad Irwin has written a super useful <a href="https://github.com/ConradIrwin/ruby-source_map">source map gem</a> for all you Ruby users</li>
<li>Some further reading on <a href="http://blog.getfirebug.com/2009/08/11/give-your-eval-a-name-with-sourceurl/">eval naming</a> and the <a href="http://www.alertdebugging.com/2009/04/29/building-a-better-javascript-profiler-with-webkit/">displayName property</a></li>
<li>You can check out the <a href="http://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java">Closure Compilers source</a> for creating source maps</li>
<li>There are some screenshots and talk of support for <a href="https://plus.google.com/110412141990454266397/posts/iqXo5AyHkyd">GWT source maps</a></li>
<li>Mozilla has a wiki entry on <a href="https://wiki.mozilla.org/DevTools/Features/CSSSourceMap">CSS Source Maps</a></li>
</ul>
<p>Source maps are a very powerful utility in a developer&#8217;s tool set. It&#8217;s super useful to be able to keep your web app lean but easily debuggable. It&#8217;s also a very powerful learning tool for newer developers to see how experienced devs structure and write their apps without having to wade through unreadable minified code. What are you waiting for? Start generating source maps for all projects now!</p>
<p class="shorty01">Short URL: <a href="http://cssn.in/ja/039">http://cssn.in/ja/039</a></p>
<div class="clear">&nbsp;</div>
]]></content:encoded>
			<wfw:commentRss>http://www.thecssninja.com/javascript/source-mapping/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.thecssninja.com/javascript/source-mapping</feedburner:origLink></item>
		<item>
		<title>A short Modernizr course</title>
		<link>http://feedproxy.google.com/~r/TheCSSNinja/~3/35kGp_2iahY/modernizr-course</link>
		<comments>http://www.thecssninja.com/javascript/modernizr-course#comments</comments>
		<pubDate>Wed, 11 Jan 2012 22:57:34 +0000</pubDate>
		<dc:creator>Ryan Seddon</dc:creator>
				<category><![CDATA[css]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.thecssninja.com/?p=955</guid>
		<description><![CDATA[Last year, I did a quick 5 min presentation on some of the features available in Modernizr for Web Directions What Do You Know event. From there, Sitepoint &#038; Learnable&#8217;s Kevin Yank asked me to put together a short course for learnable.com based on the presentation. So after working on the occasional weekend I put [...]]]></description>
			<content:encoded><![CDATA[<p>Last year, I did a quick 5 min presentation on some of the features available in Modernizr for <a href="http://whatdoyouknow.webdirections.org/videos/all-up-in-your-grill-with-modernizr"><em>Web Directions What Do You Know</em></a> event. From there, Sitepoint &#038; Learnable&#8217;s Kevin Yank asked me to put together a short course for <a href="http://learnable.com">learnable.com</a> based on the presentation. So after working on the occasional weekend I put it all together and got it launched just before xmas 2011.<span id="more-955"></span></p>
<div class="clear">&nbsp;</div>
<p><a href="https://learnable.com/courses/modernizr-front-end-development-done-right-2561"><img src="http://www.thecssninja.com/wp-content/uploads/2012/01/mzr_sml.png" alt="Modernizr: front-end development done right" width="609" height="207" class="article-img main-img" /></a></p>
<p><a href="https://learnable.com/courses/modernizr-front-end-development-done-right-2561">Go check it out</a>! <del datetime="2012-04-27T00:42:00+00:00">As a thank you for reading I will give away some free passes to the first 10 people who can answer this question correctly:</del> Promotion has now ended, thanks!</p>
<p>&#8220;Who created the Modernizr project?&#8221;</p>
<p>Mention me on twitter, <a href="http://twitter.com/ryanseddon">@ryanseddon</a>, with your answer to the question.</p>
<p>I will let the winners know via twitter.</p>
<p>If you don&#8217;t answer in time, don&#8217;t fret! It&#8217;s super cheap to get access to <a href="https://learnable.com/courses/modernizr-front-end-development-done-right-2561">my course</a> and many others at <a href="http://learnable.com">learnable.com</a>, 2012 is the year of upskilling so get onto it!</p>
<p class="shorty01">Short URL: <a href="http://cssn.in/ja/038">http://cssn.in/ja/038</a></p>
<div class="clear">&nbsp;</div>
]]></content:encoded>
			<wfw:commentRss>http://www.thecssninja.com/javascript/modernizr-course/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.thecssninja.com/javascript/modernizr-course</feedburner:origLink></item>
		<item>
		<title>Playing with the clipboard in iOS safari</title>
		<link>http://feedproxy.google.com/~r/TheCSSNinja/~3/ZDyIUcRLBes/ios-clipboard</link>
		<comments>http://www.thecssninja.com/javascript/ios-clipboard#comments</comments>
		<pubDate>Wed, 21 Dec 2011 10:33:16 +0000</pubDate>
		<dc:creator>Ryan Seddon</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.thecssninja.com/?p=940</guid>
		<description><![CDATA[So the other day it hit me that since iOS safari supports contenteditbale it should surely have support the clipboard events and other handy bits and pieces. Like any good hacker I created a testcase to find out basic support of events and getting selection range values, and as expected the support is pretty good. [...]]]></description>
			<content:encoded><![CDATA[<p>So the other day it hit me that since iOS safari supports contenteditbale it should surely have support the clipboard events and other handy bits and pieces. Like any good hacker I created a <a href="http://www.thecssninja.com/demo/clipboard/">testcase</a> to find out basic support of events and getting selection range values, and as expected the support is pretty good. Let&#8217;s dive deeper.<span id="more-940"></span></p>
<div class="clear">&nbsp;</div>
<div class="resources01"><a href="http://www.thecssninja.com/demo/clipboard/" title="Playing with the clipboard in iOS safari" class="demo" target="_blank">View a live demo</a> <a href="http://www.thecssninja.com/demo/clipboard/clipboard.zip" title="Download the source of the Playing with the clipboard in iOS safari demo" class="demo source" target="_blank">Download the source files</a></div>
<h2 class="subtitle02">Clipboard events</h2>
<p>The testcase above hooks into six events that will trigger when the user does a clipboard operation, unfortunately the before[cut/copy/paste] events don&#8217;t seem to trigger.</p>
<h2 class="subtitle02">Range objects</h2>
<p>Range objects are what you&#8217;ve selected on the page allowing you to alter the selection or simply just return what a user has selected. Ranges also allow you to programmatically set a selection within your document, both of these work in iOS safari.</p>
<p>When setting a range iOS Safari won&#8217;t actually show the selection as highlighted but if you were to check the document selection it would return the correct content, desktop browsers will show the range selected in the document. </p>
<p>However if you do the same with a user action like tapping the &#8220;set selection range&#8221; button in the demo the iOS highlight will show up. Another interesting quirk is if I tap the content and bring the keyboard up but don&#8217;t dismiss it then refresh the page the programmatically set selection will show the iOS selection highlight.</p>
<p>Another interesting find is if you perform <code>execCommand</code>, which I&#8217;ll touch on later in the article, like bold it will apply the command to the selection made and make the iOS selection UI appear.</p>
<div class="code syntax">
<pre><span class="kd">var</span> <span class="nx">sel</span> <span class="o">=</span> <span class="nb">window</span><span class="p">.</span><span class="nx">getSelection</span><span class="p">(),</span>
    <span class="nx">range</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">createRange</span><span class="p">();</span>

<span class="nx">range</span><span class="p">.</span><span class="nx">setStart</span><span class="p">(</span><span class="nx">$</span><span class="p">(</span><span class="s2">"h1"</span><span class="p">)[</span><span class="mi">0</span><span class="p">].</span><span class="nx">firstChild</span><span class="p">,</span> <span class="mi">5</span><span class="p">);</span>
<span class="nx">range</span><span class="p">.</span><span class="nx">setEnd</span><span class="p">(</span><span class="nx">$</span><span class="p">(</span><span class="s2">"p"</span><span class="p">)[</span><span class="mi">2</span><span class="p">].</span><span class="nx">firstChild</span><span class="p">,</span> <span class="mi">50</span><span class="p">);</span>
<span class="nx">sel</span><span class="p">.</span><span class="nx">removeAllRanges</span><span class="p">();</span>
<span class="nx">sel</span><span class="p">.</span><span class="nx">addRange</span><span class="p">(</span><span class="nx">range</span><span class="p">);</span>
</pre>
</div>
<p>You&#8217;ll notice that when selecting an element I get its <code>firstChild</code>, which is a textnode, this is so the offset value will work and allows you to select half a textnode. </p>
<p>The code is saying create a range starting at the documents first h1 element offsetting the selection by 5 characters and ending at the 3rd paragraph offsetting the end of the paragraph by 50 characters.</p>
<h2 class="subtitle02">Setting clipboard data</h2>
<p>Accessing the clipboard is an incredibly sporadic task, there is sort of access in some browsers. IE has the most consistent behaviour similar to how DnD data setting works you have a <code>clipboardData</code> interface which has get and <code>setData</code> methods on it. Other browsers have semi-reversed engineered the IE API with the exception that <code>clipboardData</code> is on the event object rather than the window. iOS Safari allows you to get the clipboard data on a paste event but doesn&#8217;t allow you to set it.</p>
<p>There is hope that clipboard access will one day have some consistent support through the <a href="http://dev.w3.org/2006/webapi/clipops/">Clipboard API editor spec</a> but that&#8217;s a long way off for now.</p>
<p>In the demo if you&#8217;ve copied text from another location and paste it it will alert the clipboard contents before being pasted.</p>
<div class="code syntax">
<pre><span class="k">if</span><span class="p">(</span><span class="s2">"clipboardData"</span> <span class="k">in</span> <span class="nx">e</span> <span class="o">&amp;&amp;</span> <span class="nx">e</span><span class="p">.</span><span class="nx">type</span> <span class="o">===</span> <span class="s2">"paste"</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">alert</span><span class="p">(</span><span class="s2">"Clipboard data: "</span> <span class="o">+</span> <span class="nx">e</span><span class="p">.</span><span class="nx">clipboardData</span><span class="p">.</span><span class="nx">getData</span><span class="p">(</span><span class="s1">'text/plain'</span><span class="p">));</span>
<span class="p">}</span>
</pre>
</div>
<h2 class="subtitle02">WYSIWYG</h2>
<p>By adding support for the contenteditable attribute comes a whole swoth of API&#8217;s available for manipulating the contents, one of those is execCommand.</p>
<p><code>execCommand</code> allows you to do a whole bunch things to the content. Take a look at this <a href="http://help.dottoro.com/larpvnhw.php">great resource</a> which shows all the commands available and its support in the major browsers. These commands allow you to manipulate the style and html of the editable content (this is how all those fancy WYSIWYG editors work).</p>
<p>I would be keen to know if this works on other smart phone browsers, leave a comment if you know more details.</p>
<p class="shorty01">Short URL: <a href="http://cssn.in/ja/037">http://cssn.in/ja/037</a></p>
<div class="clear">&nbsp;</div>
]]></content:encoded>
			<wfw:commentRss>http://www.thecssninja.com/javascript/ios-clipboard/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.thecssninja.com/javascript/ios-clipboard</feedburner:origLink></item>
		<item>
		<title>addEventListener, handleEvent and passing objects</title>
		<link>http://feedproxy.google.com/~r/TheCSSNinja/~3/McLCD3Cug4s/handleevent</link>
		<comments>http://www.thecssninja.com/javascript/handleevent#comments</comments>
		<pubDate>Fri, 21 Oct 2011 09:47:20 +0000</pubDate>
		<dc:creator>Ryan Seddon</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.thecssninja.com/?p=898</guid>
		<description><![CDATA[Here&#8217;s a super awesome trick I had no idea about until someone pointed out you could do this. addEventListener can take an object as a second argument that will look for a method called handleEvent and call it! No need for binding &#8220;this&#8221; so it will pass around the context correctly, the context is the [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a super awesome trick I had no idea about until someone pointed out you could do this. <code>addEventListener</code> can take an object as a second argument that will look for a method called <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener-handleEvent"><code>handleEvent</code></a> and call it! No need for binding &#8220;this&#8221; so it will pass around the context correctly, the context is the object you&#8217;ve just set as the event listener callback.<span id="more-898"></span></p>
<div class="clear">&nbsp;</div>
<div class="code">
<pre style='color:#d1d1d1;background:#000000;'><span style='color:#e66170; font-weight:bold; '>var</span> obj <span style='color:#d2cd86; '>=</span> <span style='color:#b060b0; '>{</span>
    handleEvent<span style='color:#b060b0; '>:</span> <span style='color:#e66170; font-weight:bold; '>function</span><span style='color:#d2cd86; '>(</span><span style='color:#d2cd86; '>)</span> <span style='color:#b060b0; '>{</span>
        alert<span style='color:#d2cd86; '>(</span><span style='color:#e66170; font-weight:bold; '>this</span><span style='color:#d2cd86; '>.</span>dude<span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
    <span style='color:#b060b0; '>}</span><span style='color:#d2cd86; '>,</span>
    dude<span style='color:#b060b0; '>:</span> <span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>holla</span><span style='color:#02d045; '>"</span>
<span style='color:#b060b0; '>}</span><span style='color:#b060b0; '>;</span>

element<span style='color:#d2cd86; '>.</span>addEventListener<span style='color:#d2cd86; '>(</span><span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>click</span><span style='color:#02d045; '>"</span><span style='color:#d2cd86; '>,</span> obj<span style='color:#d2cd86; '>,</span> <span style='color:#0f4d75; '>false</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
</pre>
</div>
<div class="resources01"><a target="_blank" class="demo" title="A demo showing handleEvent" href="http://www.thecssninja.com/demo/handleEvent/">View a live demo</a> <a target="_blank" class="demo source" title="Download the source of the handleEvent demo" href="http://www.thecssninja.com/demo/handleEvent/handleEvent.zip">Download the source files</a></div>
<h2 class="subtitle02">Why is this awesome?</h2>
<p>We can do things like this:</p>
<div class="code">
<pre style='color:#d1d1d1;background:#000000;'><span style='color:#e66170; font-weight:bold; '>var</span> obj  <span style='color:#d2cd86; '>=</span>  <span style='color:#b060b0; '>{</span>
    init<span style='color:#b060b0; '>:</span> <span style='color:#e66170; font-weight:bold; '>function</span><span style='color:#d2cd86; '>(</span><span style='color:#d2cd86; '>)</span> <span style='color:#b060b0; '>{</span>
        document<span style='color:#d2cd86; '>.</span>getElementById<span style='color:#d2cd86; '>(</span><span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>btn</span><span style='color:#02d045; '>"</span><span style='color:#d2cd86; '>)</span><span style='color:#d2cd86; '>.</span>addEventListener<span style='color:#d2cd86; '>(</span><span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>click</span><span style='color:#02d045; '>"</span><span style='color:#d2cd86; '>,</span> <span style='color:#e66170; font-weight:bold; '>this</span><span style='color:#d2cd86; '>,</span> <span style='color:#0f4d75; '>false</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
        document<span style='color:#d2cd86; '>.</span>getElementById<span style='color:#d2cd86; '>(</span><span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>btn</span><span style='color:#02d045; '>"</span><span style='color:#d2cd86; '>)</span><span style='color:#d2cd86; '>.</span>addEventListener<span style='color:#d2cd86; '>(</span><span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>touchstart</span><span style='color:#02d045; '>"</span><span style='color:#d2cd86; '>,</span> <span style='color:#e66170; font-weight:bold; '>this</span><span style='color:#d2cd86; '>,</span> <span style='color:#0f4d75; '>false</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
    <span style='color:#b060b0; '>}</span><span style='color:#d2cd86; '>,</span>
    handleEvent<span style='color:#b060b0; '>:</span> <span style='color:#e66170; font-weight:bold; '>function</span><span style='color:#d2cd86; '>(</span>e<span style='color:#d2cd86; '>)</span> <span style='color:#b060b0; '>{</span>
        <span style='color:#e66170; font-weight:bold; '>switch</span><span style='color:#d2cd86; '>(</span>e<span style='color:#d2cd86; '>.</span>type<span style='color:#d2cd86; '>)</span> <span style='color:#b060b0; '>{</span>
            <span style='color:#e66170; font-weight:bold; '>case</span> <span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>click</span><span style='color:#02d045; '>"</span><span style='color:#b060b0; '>:</span>
                <span style='color:#e66170; font-weight:bold; '>this</span><span style='color:#d2cd86; '>.</span>button<span style='color:#d2cd86; '>(</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
                <span style='color:#e66170; font-weight:bold; '>break</span><span style='color:#b060b0; '>;</span>
            <span style='color:#e66170; font-weight:bold; '>case</span> <span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>touchstart</span><span style='color:#02d045; '>"</span><span style='color:#b060b0; '>:</span>
                <span style='color:#e66170; font-weight:bold; '>this</span><span style='color:#d2cd86; '>.</span>button<span style='color:#d2cd86; '>(</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
                <span style='color:#e66170; font-weight:bold; '>break</span><span style='color:#b060b0; '>;</span>
        <span style='color:#b060b0; '>}</span>
    <span style='color:#b060b0; '>}</span><span style='color:#d2cd86; '>,</span>
    dude<span style='color:#b060b0; '>:</span> <span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>holla</span><span style='color:#02d045; '>"</span><span style='color:#d2cd86; '>,</span>
    button<span style='color:#b060b0; '>:</span> <span style='color:#e66170; font-weight:bold; '>function</span><span style='color:#d2cd86; '>(</span><span style='color:#d2cd86; '>)</span> <span style='color:#b060b0; '>{</span>
        alert<span style='color:#d2cd86; '>(</span><span style='color:#e66170; font-weight:bold; '>this</span><span style='color:#d2cd86; '>.</span>dude<span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
    <span style='color:#b060b0; '>}</span>
<span style='color:#b060b0; '>}</span><span style='color:#b060b0; '>;</span>

obj<span style='color:#d2cd86; '>.</span>init<span style='color:#d2cd86; '>(</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
</pre>
</div>
<p>As you can see our object has an <code>init()</code> method which binds all the events and just passes in &#8220;this&#8221; as the callback, <code>handleEvent</code> then delegates off to whatever method it needs based on the event being triggered, rad.</p>
<h2 class="subtitle02">But wait there&#8217;s more</h2>
<p>Another awesome thing we can do is change the buttons behaviour without having to remove and re-attach the event handler. The second button in the demo changes what the first button does by redefining the handleEvent method. </p>
<div class="code">
<pre style='color:#d1d1d1;background:#000000;'>changeHandleEvent<span style='color:#b060b0; '>:</span> <span style='color:#e66170; font-weight:bold; '>function</span><span style='color:#d2cd86; '>(</span>evt<span style='color:#d2cd86; '>)</span> <span style='color:#b060b0; '>{</span>
    <span style='color:#e66170; font-weight:bold; '>this</span><span style='color:#d2cd86; '>.</span>_handleEvent <span style='color:#d2cd86; '>=</span> <span style='color:#e66170; font-weight:bold; '>this</span><span style='color:#d2cd86; '>.</span>handleEvent<span style='color:#b060b0; '>;</span>
    <span style='color:#9999a9; '>// Change the the handleEvent method without needing to remove </span>
    <span style='color:#9999a9; '>// and re-attach the event(s)</span>
    <span style='color:#e66170; font-weight:bold; '>this</span><span style='color:#d2cd86; '>.</span>handleEvent <span style='color:#d2cd86; '>=</span> <span style='color:#e66170; font-weight:bold; '>function</span><span style='color:#d2cd86; '>(</span>e<span style='color:#d2cd86; '>)</span> <span style='color:#b060b0; '>{</span>
        <span style='color:#e66170; font-weight:bold; '>var</span> t <span style='color:#d2cd86; '>=</span> evt<span style='color:#d2cd86; '>.</span>target<span style='color:#b060b0; '>;</span>

        <span style='color:#e66170; font-weight:bold; '>if</span> <span style='color:#d2cd86; '>(</span>t<span style='color:#d2cd86; '>.</span>id <span style='color:#d2cd86; '>===</span> <span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>btn</span><span style='color:#02d045; '>"</span><span style='color:#d2cd86; '>)</span> <span style='color:#b060b0; '>{</span>
            <span style='color:#9999a9; '>// Check the button being clicked and do new stuff</span>
        <span style='color:#b060b0; '>}</span> <span style='color:#e66170; font-weight:bold; '>else</span> <span style='color:#e66170; font-weight:bold; '>if</span><span style='color:#d2cd86; '>(</span>t<span style='color:#d2cd86; '>.</span>id <span style='color:#d2cd86; '>===</span> <span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>btn3</span><span style='color:#02d045; '>"</span><span style='color:#d2cd86; '>)</span> <span style='color:#b060b0; '>{</span>
            <span style='color:#e66170; font-weight:bold; '>this</span><span style='color:#d2cd86; '>.</span>revertHandleEvent<span style='color:#d2cd86; '>(</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
        <span style='color:#b060b0; '>}</span>
    <span style='color:#b060b0; '>}</span>
<span style='color:#b060b0; '>}</span>
</pre>
</div>
<p>Makes for some pretty powerful stuff. The third button re-instates the first buttons behaviour back to its original form.</p>
<p>This works in nearly all browsers that support addEventListener, Blackberry 6 browser being one that doesn&#8217;t. Blackberry OS7 has fixed this bug.</p>
<h2 class="subtitle02">Polyfill it</h2>
<p>IE9 was the first to support addEventListener + handleEvent in the IE family, so for the older ones we can polyfill in support for &lt;IE8 and other non-supporting browsers (BBOS6).</p>
<div class="code">
<pre style='color:#d1d1d1;background:#000000;'><span style='color:#9999a9; '>// fn arg can be an object or a function, thanks to handleEvent</span>
<span style='color:#e66170; font-weight:bold; '>function</span> on<span style='color:#d2cd86; '>(</span>el<span style='color:#d2cd86; '>,</span> evt<span style='color:#d2cd86; '>,</span> fn<span style='color:#d2cd86; '>,</span> bubble<span style='color:#d2cd86; '>)</span> <span style='color:#b060b0; '>{</span>
    <span style='color:#e66170; font-weight:bold; '>if</span><span style='color:#d2cd86; '>(</span><span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>addEventListener</span><span style='color:#02d045; '>"</span> <span style='color:#e66170; font-weight:bold; '>in</span> el<span style='color:#d2cd86; '>)</span> <span style='color:#b060b0; '>{</span>
        <span style='color:#9999a9; '>// BBOS6 doesn't support handleEvent, catch and polyfill</span>
        <span style='color:#e66170; font-weight:bold; '>try</span> <span style='color:#b060b0; '>{</span>
            el<span style='color:#d2cd86; '>.</span>addEventListener<span style='color:#d2cd86; '>(</span>evt<span style='color:#d2cd86; '>,</span> fn<span style='color:#d2cd86; '>,</span> bubble<span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
        <span style='color:#b060b0; '>}</span> <span style='color:#e66170; font-weight:bold; '>catch</span><span style='color:#d2cd86; '>(</span>e<span style='color:#d2cd86; '>)</span> <span style='color:#b060b0; '>{</span>
            <span style='color:#e66170; font-weight:bold; '>if</span><span style='color:#d2cd86; '>(</span><span style='color:#e66170; font-weight:bold; '>typeof</span> fn <span style='color:#d2cd86; '>==</span> <span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>object</span><span style='color:#02d045; '>"</span> <span style='color:#d2cd86; '>&amp;&amp;</span> fn<span style='color:#d2cd86; '>.</span>handleEvent<span style='color:#d2cd86; '>)</span> <span style='color:#b060b0; '>{</span>
                el<span style='color:#d2cd86; '>.</span>addEventListener<span style='color:#d2cd86; '>(</span>evt<span style='color:#d2cd86; '>,</span> <span style='color:#e66170; font-weight:bold; '>function</span><span style='color:#d2cd86; '>(</span>e<span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>{</span>
                    <span style='color:#9999a9; '>// Bind fn as this and set first arg as event object</span>
                    fn<span style='color:#d2cd86; '>.</span>handleEvent<span style='color:#d2cd86; '>.</span>call<span style='color:#d2cd86; '>(</span>fn<span style='color:#d2cd86; '>,</span>e<span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
                <span style='color:#b060b0; '>}</span><span style='color:#d2cd86; '>,</span> bubble<span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
            <span style='color:#b060b0; '>}</span> <span style='color:#e66170; font-weight:bold; '>else</span> <span style='color:#b060b0; '>{</span>
                <span style='color:#e66170; font-weight:bold; '>throw</span> e<span style='color:#b060b0; '>;</span>
            <span style='color:#b060b0; '>}</span>
        <span style='color:#b060b0; '>}</span>
    <span style='color:#b060b0; '>}</span> <span style='color:#e66170; font-weight:bold; '>else</span> <span style='color:#e66170; font-weight:bold; '>if</span><span style='color:#d2cd86; '>(</span><span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>attachEvent</span><span style='color:#02d045; '>"</span> <span style='color:#e66170; font-weight:bold; '>in</span> el<span style='color:#d2cd86; '>)</span> <span style='color:#b060b0; '>{</span>
        <span style='color:#9999a9; '>// check if the callback is an object and contains handleEvent</span>
        <span style='color:#e66170; font-weight:bold; '>if</span><span style='color:#d2cd86; '>(</span><span style='color:#e66170; font-weight:bold; '>typeof</span> fn <span style='color:#d2cd86; '>==</span> <span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>object</span><span style='color:#02d045; '>"</span> <span style='color:#d2cd86; '>&amp;&amp;</span> fn<span style='color:#d2cd86; '>.</span>handleEvent<span style='color:#d2cd86; '>)</span> <span style='color:#b060b0; '>{</span>
            el<span style='color:#d2cd86; '>.</span>attachEvent<span style='color:#d2cd86; '>(</span><span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>on</span><span style='color:#02d045; '>"</span> <span style='color:#d2cd86; '>+</span> evt<span style='color:#d2cd86; '>,</span> <span style='color:#e66170; font-weight:bold; '>function</span><span style='color:#d2cd86; '>(</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>{</span>
                <span style='color:#9999a9; '>// Bind fn as this</span>
                fn<span style='color:#d2cd86; '>.</span>handleEvent<span style='color:#d2cd86; '>.</span>call<span style='color:#d2cd86; '>(</span>fn<span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
            <span style='color:#b060b0; '>}</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
        <span style='color:#b060b0; '>}</span> <span style='color:#e66170; font-weight:bold; '>else</span> <span style='color:#b060b0; '>{</span>
            el<span style='color:#d2cd86; '>.</span>attachEvent<span style='color:#d2cd86; '>(</span><span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>on</span><span style='color:#02d045; '>"</span> <span style='color:#d2cd86; '>+</span> evt<span style='color:#d2cd86; '>,</span> fn<span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
        <span style='color:#b060b0; '>}</span>
    <span style='color:#b060b0; '>}</span>
<span style='color:#b060b0; '>}</span>
</pre>
</div>
<p>For oldIE it checks if the callback is an object and if it contains <code>handleEvent</code>. Using call we can change the &#8220;this&#8221; context to the object passed. </p>
<p>For BBOS6 we wrap a try catch around addEventListener and if the attaching throws, check the callback is an object and has the handleEvent method otherwise don&#8217;t swallow the error.</p>
<p>We handle all this by wrapping up the event attaching into a nice method which handles the process for us.</p>
<h2 class="subtitle02">Resources</h2>
<p>I&#8217;m certainly not the first to document this, see <a href="http://ajaxian.com/archives/an-alternative-way-to-addeventlistener">ajaxian article</a> with some great examples.</p>
<p>Even HTML5 boilerplate mobile uses <a href="https://github.com/h5bp/mobile-boilerplate/blob/master/js/mylibs/helper.js#L70">this technique</a> for their fast touch event handling.</p>
<p class="shorty01">Short URL: <a href="http://cssn.in/ja/036">http://cssn.in/ja/036</a></p>
<div class="clear">&nbsp;</div>
]]></content:encoded>
			<wfw:commentRss>http://www.thecssninja.com/javascript/handleevent/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://www.thecssninja.com/javascript/handleevent</feedburner:origLink></item>
		<item>
		<title>Fullscreen HTML5 video</title>
		<link>http://feedproxy.google.com/~r/TheCSSNinja/~3/pinbW6HLo5E/fullscreen</link>
		<comments>http://www.thecssninja.com/javascript/fullscreen#comments</comments>
		<pubDate>Mon, 10 Oct 2011 09:38:10 +0000</pubDate>
		<dc:creator>Ryan Seddon</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.thecssninja.com/?p=882</guid>
		<description><![CDATA[In preparation for a talk I&#8217;m doing at Web Directions South I needed to be able to put video into fullscreen mode from within my HTML based slides. In order to do this I imagined I would of needed to use flash but thankfully Webkit nightly, Chrome dev and Firefox nightly have added the ability [...]]]></description>
			<content:encoded><![CDATA[<p>In preparation for a talk I&#8217;m doing at <a href="south11.webdirections.org/program/development#remote-debugging-landscape" title="Remote debugging landscape">Web Directions South</a> I needed to be able to put video into fullscreen mode from within my HTML based slides. In order to do this I imagined I would of needed to use flash but thankfully Webkit nightly, Chrome dev and Firefox nightly have added the ability to put HTML5 videos, and other elements, into fullscreen mode using javascript. The <a href="http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html" title="FullScreen Editor Draft API specification">FullScreen API</a> now updated to point to official editor draft, thanks <a href="#comment-2743">Hans</a>!.<br />
<span id="more-882"></span></p>
<h2 class="subtitle02">Fullscreen, finally</h2>
<p>HTML5 video has come a long way but still lacks consistent codec support and the ability to go fullscreen, until now of course.</p>
<div class="resources01"><a target="_blank" class="demo" title="Using the Fullscreen API" href="http://www.thecssninja.com/demo/fullscreen/">View a live demo</a> <a target="_blank" class="demo source" title="Download the source of the fullscreen demo" href="http://www.thecssninja.com/demo/fullscreen/fullscreen.zip">Download the source files</a></div>
<p>As you can see I&#8217;ve created a very simple demo showing HTML5 video in full screen, make sure you&#8217;re using Chrome dev, webkit or firefox nightly. In Firefox you&#8217;ll need to enable it in about:config, search for <strong>&#8220;full-screen-api.enabled&#8221;</strong> and set it to true. Webkit nightly will require the <strong>&#8220;&#8211;enable-fullscreen-api&#8221;</strong> flag when launching. Chrome dev has it enabled by default.</p>
<h2 class="subtitle02">API differences</h2>
<p>If you poked around the source you&#8217;ll notice that Webkit uses <del datetime="2011-10-16T06:15:46+00:00">slightly different method to trigger fullscreen.</del> <ins datetime="2011-10-16T06:15:46+00:00">Turns out webkit only uses a different API for videos but uses the same as firefox for all other elements.</ins> Mozilla initially created a draft spec for <a href="https://wiki.mozilla.org/index.php?title=Gecko:FullScreenAPI" title="Proposed FullScreen API specification">fullscreen elements</a> but Webkit decided to change the name slightly, for the better I think.</p>
<div class="code">
<pre style='color:#d1d1d1;background:#000000;' lang="javascript"><span style='color:#e66170; font-weight:bold; '>var</span> video <span style='color:#d2cd86; '>=</span> document<span style='color:#d2cd86; '>.</span>getElementById<span style='color:#d2cd86; '>(</span><span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>video</span><span style='color:#02d045; '>"</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>

<span style='color:#9999a9; '>// Mozilla</span>
video<span style='color:#d2cd86; '>.</span>mozRequestFullScreen<span style='color:#d2cd86; '>(</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>

<span style='color:#9999a9; '>// Webkit for video elements only</span>
video<span style='color:#d2cd86; '>.</span>webkitEnterFullScreen<span style='color:#d2cd86; '>(</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
</pre>
</div>
<p>As with entering fullscreen you can also cancel it. Using the cancelFullScreen method will exit any element currently in fullscreen mode.</p>
<div class="code">
<pre style='color:#d1d1d1;background:#000000;'><span style='color:#9999a9; '>// Mozilla</span>
video<span style='color:#d2cd86; '>.</span>mozCancelFullScreen<span style='color:#d2cd86; '>(</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>

<span style='color:#9999a9; '>// Webkit</span>
video<span style='color:#d2cd86; '>.</span>webkitCancelFullScreen<span style='color:#d2cd86; '>(</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
</pre>
</div>
<h2 class="subtitle02">Fullscreen CSS, DOM properties and events</h2>
<p>Along with the ability to force a video into fullscreen there is also some CSS pseudo-classes and DOM properties. </p>
<div class="code">
<pre style='color:#d1d1d1;background:#000000;'>video<span style='color:#b060b0; '>:</span>-webkit-full-screen     <span style='color:#b060b0; '>{</span> <span style='color:#904050; '>max-height</span><span style='color:#d2cd86; '>:</span> <span style='color:#00a800; '>100</span><span style='color:#006600; '>%</span><span style='color:#b060b0; '>;</span> <span style='color:#b060b0; '>}</span>
video<span style='color:#b060b0; '>:</span>-moz-full-screen        <span style='color:#b060b0; '>{</span> <span style='color:#904050; '>max-height</span><span style='color:#d2cd86; '>:</span> <span style='color:#00a800; '>100</span><span style='color:#006600; '>%</span><span style='color:#b060b0; '>;</span> <span style='color:#b060b0; '>}</span>
</pre>
</div>
<p>The FullScreen API adds one notable pseudo-class that lets you change the element when it&#8217;s in fullscreen mode. A good example is if you had a <code>max-height</code> set on your video element and you triggered fullscreen mode you can then reset the <code>max-height</code> to be 100%.</p>
<p>If you want to do something when the browser is in full screen mode the document object gets the <code>fullScreen</code> property. This is slightly different in webkit compared to mozilla.</p>
<div class="code">
<pre style='color:#d1d1d1;background:#000000;'><span style='color:#9999a9; '>// Mozilla</span>
document<span style='color:#d2cd86; '>.</span>mozFullscreen<span style='color:#b060b0; '>;</span>

<span style='color:#9999a9; '>// Webkit</span>
document<span style='color:#d2cd86; '>.</span>webkitIsFullscreen<span style='color:#b060b0; '>;</span>
</pre>
</div>
<p>As you can see mozilla doesn&#8217;t include the <code>Is</code> in the property like webkit does. So we have this boolean property on the document how do we know when to check it? Well luckily the API also includes an event that triggers called <code>[moz/webkit]fullscreenchange</code>.</p>
<div class="code">
<pre style='color:#d1d1d1;background:#000000;'>video<span style='color:#d2cd86; '>.</span>addEventListener<span style='color:#d2cd86; '>(</span><span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>mozfullscreenchange</span><span style='color:#02d045; '>"</span><span style='color:#d2cd86; '>,</span><span style='color:#e66170; font-weight:bold; '>function</span><span style='color:#d2cd86; '>(</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>{</span>
    console<span style='color:#d2cd86; '>.</span><span style='color:#e66170; font-weight:bold; '>log</span><span style='color:#d2cd86; '>(</span>document<span style='color:#d2cd86; '>.</span>mozFullScreen<span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
<span style='color:#b060b0; '>}</span><span style='color:#d2cd86; '>,</span> <span style='color:#0f4d75; '>false</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>

video<span style='color:#d2cd86; '>.</span>addEventListener<span style='color:#d2cd86; '>(</span><span style='color:#02d045; '>"</span><span style='color:#00c4c4; '>webkitfullscreenchange</span><span style='color:#02d045; '>"</span><span style='color:#d2cd86; '>,</span><span style='color:#e66170; font-weight:bold; '>function</span><span style='color:#d2cd86; '>(</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>{</span>
    console<span style='color:#d2cd86; '>.</span><span style='color:#e66170; font-weight:bold; '>log</span><span style='color:#d2cd86; '>(</span>document<span style='color:#d2cd86; '>.</span>webkitIsFullScreen<span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
<span style='color:#b060b0; '>}</span><span style='color:#d2cd86; '>,</span> <span style='color:#0f4d75; '>false</span><span style='color:#d2cd86; '>)</span><span style='color:#b060b0; '>;</span>
</pre>
</div>
<p>The event will trigger whenever fullscreen mode changes so you can then check the document <code>fullScreen</code> property if it&#8217;s currently in or out of fullscreen mode. The event is currently prefixed in both Webkit and Firefox.</p>
<h2 class="subtitle02">Some quirks</h2>
<p>API differences aside the mozilla spec highly recommends that hitting the Esc key will exit the browser from fullscreen, <del datetime="2011-10-18T21:49:24+00:00">unfortunately Chrome doesn&#8217;t adhere to this (<a href="http://code.google.com/p/chromium/issues/detail?id=99869">see bug</a>)</del> (Bug has been fixed for linux/windows still needs a fix for mac). If you&#8217;re on OSX Lion it will put the browser into full screen mode so to exit you have to hit <code>Cmd+Shift+F</code> on windows <code>F11</code>.</p>
<p>API changes are almost guaranteed. There is already a <a href="https://bugs.webkit.org/show_bug.cgi?id=36081">webkit bug</a> which mentions changing to &#8220;Fullscreen&#8221; rather than &#8220;FullScreen&#8221; but for now both are enabled.</p>
<p><strong>UPDATE:</strong> There is an official editor draft of the spec and looks like Mozilla&#8217;s implementation will be the final one. The API is slighty changing to make FullScreen lowercase in all API calls except where it isn&#8217;t the first word e.g. <code>requestFullscreen</code>.</p>
<h2 class="subtitle02">Much more than just video</h2>
<p>I only wanted to cover video elements in this article but the API allows fullscreen on almost any element, <del datetime="2011-10-16T06:15:46+00:00">this functionality is much more limited in Webkit.</del> <ins datetime="2011-10-16T06:15:46+00:00">Webkit uses <code>webkitRequestFullscreen</code> for all other elements.</ins> Using the <code>allowfullscreen</code> attribute on iframes for example will allow youtube or vimeo to put their iframe embeds into fullscreen mode. Firefox works with more elements in their nightly build e.g. if you add the <code>mozallowfullscreen</code> attribute to the iframe you can put it into fullscreen mode.</p>
<p>There is also some security restrictions around key events and characters allowed.</p>
<h2 class="subtitle02">Further reading</h2>
<ul>
<li>Mozilla has a <a href="http://pearce.org.nz/full-screen/">full on demo</a> showing all the support currently in nightly builds, see <a href="http://blog.pearce.org.nz/2011/09/mozilla-full-screen-api-progress-update.html">blog post</a> too.</li>
<li>Make sure to read over the <a href="http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html">editor draft spec</a>.</li>
<li>Apple developer docs mentions support for some of the <a href="http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html">events and properties</a>.</li>
<li>Check out <a href="http://mediaelementjs.com/">MEjs</a> which recently added support for the fullscreen APIs</li>
</ul>
<p class="shorty01">Short URL: <a href="http://cssn.in/ja/035">http://cssn.in/ja/035</a></p>
<div class="clear">&nbsp;</div>
]]></content:encoded>
			<wfw:commentRss>http://www.thecssninja.com/javascript/fullscreen/feed</wfw:commentRss>
		<slash:comments>19</slash:comments>
		<feedburner:origLink>http://www.thecssninja.com/javascript/fullscreen</feedburner:origLink></item>
		<item>
		<title>Handling high resolution sprite images with CSS3</title>
		<link>http://feedproxy.google.com/~r/TheCSSNinja/~3/3IN1OdYnk70/high-res-sprites</link>
		<comments>http://www.thecssninja.com/css/high-res-sprites#comments</comments>
		<pubDate>Wed, 15 Jun 2011 12:41:09 +0000</pubDate>
		<dc:creator>Ryan Seddon</dc:creator>
				<category><![CDATA[css]]></category>

		<guid isPermaLink="false">http://www.thecssninja.com/?p=851</guid>
		<description><![CDATA[The iPhone 4 has introduced a new challenge to web developers due to its retina display using a higher dpi than most devices. What looked sharp in desktop browsers and other lower dpi devices appears blurry and pixelated on the iPhone 4 and potentially other devices which will have higher dpi screens. The current solution [...]]]></description>
			<content:encoded><![CDATA[<p>The iPhone 4 has introduced a new challenge to web developers due to its retina display using a higher dpi than most devices. What looked sharp in desktop browsers and other lower dpi devices appears blurry and pixelated on the iPhone 4 and potentially other devices which will have higher dpi screens. The current solution is to have two sets of images one for general and one for high dpi screens. You then switch it up using media queries depending on the screens dpi, this has been <a href="http://blog.iwalt.com/2010/06/targeting-the-iphone-4-retina-display-with-css3-media-queries.html">documented</a> and <a href="http://www.lukew.com/ff/entry.asp?1142">discussed</a> many <a href="http://aralbalkan.com/3331">times</a>. Let&#8217;s try a different approach.<span id="more-851"></span></p>
<h2 class="subtitle02">So what&#8217;s different?</h2>
<p>The difference between my solution and others is mine requires only a single sprite image and doesn&#8217;t need a special media query to keep the images looking sharp in higher dpi screens.</p>
<div class="resources01"><a target="_blank" class="demo" title="Handling high resolution sprite images in CSS3 demonstration" href="http://www.thecssninja.com/demo/css_bgsize/">View live demo</a> <a target="_blank" class="demo source" title="Download the source of the Handling high resolution sprite images in CSS3 demo" href="http://www.thecssninja.com/demo/css_bgsize/css_bgsize.zip">Download the source files</a></div>
<p>The above demo loads a single sprite image containing all my icons needed. This image is saved with everything double the size of what it should be.</p>
<h2 class="subtitle02">How it works</h2>
<p>The way I get it to display nicely for both dpi&#8217;s is to use the CSS3 <code>background-size</code> property to shrink it down to the correct size. Since the iPhone 4 naturally scales the image up there is no artefacts or blurriness as the image is already the correct size so you don&#8217;t need to use the special media query to make it render nicely.</p>

<div class="wp_syntax"><div class="code"><pre class="css css" style="font-family:monospace;"><span style="color: #6666ff;">.ico</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">background</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">url</span><span style="color: #00AA00;">&#40;</span>ico_sprite-32x32.png<span style="color: #00AA00;">&#41;</span> <span style="color: #933;">-78px</span> <span style="color: #933;">11px</span> <span style="color: #993333;">no-repeat</span>;
    background-<span style="color: #000000; font-weight: bold;">size</span><span style="color: #00AA00;">:</span> <span style="color: #933;">96px</span> <span style="color: #993333;">auto</span>; <span style="color: #808080; font-style: italic;">/* 192/2 = 96px */</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.echeck</span>      <span style="color: #00AA00;">&#123;</span> <span style="color: #000000; font-weight: bold;">background-position</span><span style="color: #00AA00;">:</span> <span style="color: #933;">-54px</span> <span style="color: #933;">-14px</span>; <span style="color: #00AA00;">&#125;</span>
<span style="color: #6666ff;">.creditcard</span>  <span style="color: #00AA00;">&#123;</span> <span style="color: #000000; font-weight: bold;">background-position</span><span style="color: #00AA00;">:</span> <span style="color: #933;">-30px</span> <span style="color: #933;">-38px</span>; <span style="color: #00AA00;">&#125;</span>
<span style="color: #6666ff;">.cash</span>         <span style="color: #00AA00;">&#123;</span> <span style="color: #000000; font-weight: bold;">background-position</span><span style="color: #00AA00;">:</span> <span style="color: #933;">-4px</span> <span style="color: #933;">-62px</span>; <span style="color: #00AA00;">&#125;</span></pre></div></div>

<p>If your sprite image is 192px wide then you shrink the width to 96px and set the height to auto to keep the correct aspect ratio. Setting the <code>background-position</code> is also halved so if it&#8217;s 108px down you set it too -54px to get the correct offset.</p>
<p>See some comparison images.</p>
<p><a href="http://www.thecssninja.com/demo/css_bgsize/iPhone3GS-screengrab.png"><img height="270" width="180" class="article-img display-img" title="iPhone 3GS showing high resolution sprite images" alt="iPhone 3GS showing high resolution sprite images" src="http://www.thecssninja.com/demo/css_bgsize/iPhone3GS-screengrab.png"></a><a href="http://www.thecssninja.com/demo/css_bgsize/iPhone4-screengrab.png"><img height="270" width="180" class="article-img display-img" title="iPhone 4 showing high resolution sprite images" alt="iPhone 4 showing high resolution sprite images" src="http://www.thecssninja.com/demo/css_bgsize/iPhone4-screengrab.png"></a><a href="http://www.thecssninja.com/demo/css_bgsize/OperaMobile11-291DPI.png"><img height="270" width="180" class="article-img display-img" title="Opera Mobile 11 with DPI set to 291 showing high resolution sprite images" alt="Opera Mobile 11 with DPI set to 291 showing high resolution sprite images" src="http://www.thecssninja.com/demo/css_bgsize/OperaMobile11-291DPI.png"></a></p>
<p><small style="display: block;">iPhone 3GS on the left, iPhone 4 in the middle and Opera Mobile 11 with 291 DPI set on the right</small></p>
<h2 class="subtitle02">There are drawbacks</h2>
<p>Of course this isn&#8217;t perfect but in the correct situation is a much better solution. If you need to support older browsers or less capable then <code>background-size</code> won&#8217;t work, see <a href="http://caniuse.com/#search=background-size">background-size support</a>. There is also file size being larger since the sprite image is double the resolution the image is roughly 30-50% larger in size than the smaller counterpart if you&#8217;re working with a 8bit png.</p>
<p class="shorty01">Short URL: <a href="http://cssn.in/ja/034">http://cssn.in/ja/034</a></p>
<div class="clear">&nbsp;</div>
]]></content:encoded>
			<wfw:commentRss>http://www.thecssninja.com/css/high-res-sprites/feed</wfw:commentRss>
		<slash:comments>16</slash:comments>
		<feedburner:origLink>http://www.thecssninja.com/css/high-res-sprites</feedburner:origLink></item>
		<item>
		<title>I scope, you scope, we all scope for NoScope! JS style element injection quirks in IE</title>
		<link>http://feedproxy.google.com/~r/TheCSSNinja/~3/hoCpchcDLvQ/noscope</link>
		<comments>http://www.thecssninja.com/javascript/noscope#comments</comments>
		<pubDate>Wed, 13 Apr 2011 12:18:09 +0000</pubDate>
		<dc:creator>Ryan Seddon</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.thecssninja.com/?p=831</guid>
		<description><![CDATA[The other day I was writing some updates and improvements for Modernizr, one to detect for generated content support and two to improve stylesheet and element injection. Modernizr already in a few places inserts a stylesheet and a corresponding element to do some tests e.g. generatedcontent, touch, css3transforms and a few others. All this happened [...]]]></description>
			<content:encoded><![CDATA[<p>The other day I was writing some updates and improvements for <a href="http://www.modernizr.com/">Modernizr</a>, one to detect for generated content support and two to improve stylesheet and element injection. Modernizr already in a few places inserts a stylesheet and a corresponding element to do some tests e.g. generatedcontent, touch, css3transforms and a few others. All this happened multiple times; each test would inject an element and an inline style element, do its test then remove both elements. All this happens while the page is loading and as you can see the more tests that involve these steps exponentially grow the number of times it needs to touch the DOM.<span id="more-831"></span></p>
<p>Modernizrs&#8217; previous method of injecting the elements revolves around forking for IE, IE<9 uses <code>addRule()</code> rather than <code>insertRule()</code>, this makes it hard to write a simple re-useable method for doing such a test that is cross browser. So I began thinking how this could be re-written to be simplified for re-usability. Rather than inject a style element into the head of a document we could use <code>innerHTML</code> and inject into the element that Modernizr will test against.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;">elem.<span style="color: #660066;">innerHTML</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;&lt;style&gt;&quot;</span><span style="color: #339933;">+</span>css<span style="color: #339933;">+</span><span style="color: #3366CC;">&quot;&lt;/style&gt;&quot;</span>;
doc.<span style="color: #660066;">appendChild</span><span style="color: #009900;">&#40;</span>elem<span style="color: #009900;">&#41;</span>;</pre></div></div>

<p>Simple, easy and certainly re-usable. But something that stumped me for a while is IE6-9 would not append the style element inside the test element?</p>
<h2 class="subtitle02">IE and the case of the NoScope element</h2>
<p>After searching high and low I found some useful information about scope and <a href="http://msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx">NoScope</a> elements in IE. Basically IE has a few elements that are considered NoScope which when trying to insert with <code>innerHTML</code> will be stripped! On this infamous page however it mentions if you precede a NoScope element with a scoped element they will not be stripped and we can then insert our style element.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;">elem.<span style="color: #660066;">innerHTML</span> <span style="color: #339933;">=</span> scopeElem<span style="color: #339933;">+</span><span style="color: #3366CC;">&quot;&lt;style&gt;&quot;</span><span style="color: #339933;">+</span>css<span style="color: #339933;">+</span><span style="color: #3366CC;">&quot;&lt;/style&gt;&quot;</span>;
doc.<span style="color: #660066;">appendChild</span><span style="color: #009900;">&#40;</span>elem<span style="color: #009900;">&#41;</span>;</pre></div></div>

<p>Huzzah! It works in IE6-9. We now have a simpler easier way to inject an element with associative styles and we've halved our touching of the DOM by bundling the test element and style element into one <code>appendChild</code> operation.</p>
<h2 class="subtitle02">What's considered a scoped element?</h2>
<p>A scoped element can be anything other than a style, script or comment element. In Modernizrs' case it uses the soft hyphen entity (&amp;shy;) so as not to interfere with measurements done on the injected element. We could very well prepend the <code>innerHTML</code> string with the test element we wish to inject, but for easier referencing I create it in the method and pass it to the callback. This way we can keep the reference to the node and not have to query the DOM again.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;">injectElementWithStyles <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>rule<span style="color: #339933;">,</span>callback<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    ...
    <span style="color: #003366; font-weight: bold;">var</span> style<span style="color: #339933;">,</span> div <span style="color: #339933;">=</span> document.<span style="color: #660066;">createElement</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'div'</span><span style="color: #009900;">&#41;</span>;
&nbsp;
    style <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #3366CC;">'&amp;shy;'</span><span style="color: #339933;">,</span><span style="color: #3366CC;">'&lt;style&gt;'</span><span style="color: #339933;">,</span>rule<span style="color: #339933;">,</span><span style="color: #3366CC;">'&lt;/style&gt;'</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">join</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">''</span><span style="color: #009900;">&#41;</span>;
    div.<span style="color: #660066;">id</span> <span style="color: #339933;">=</span> mod;
    div.<span style="color: #660066;">innerHTML</span> <span style="color: #339933;">+=</span> style;
    docElement.<span style="color: #660066;">appendChild</span><span style="color: #009900;">&#40;</span>div<span style="color: #009900;">&#41;</span>;
&nbsp;
    ret <span style="color: #339933;">=</span> callback<span style="color: #009900;">&#40;</span>div<span style="color: #339933;">,</span>rule<span style="color: #009900;">&#41;</span>;
    ...
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>There's also a few other additions that centre around the <code>injectElementWithStyles()</code> method such as the <code>test_bundle()</code> method which does the DOM injection test in one fell swoop. If you want to know more go check out the <a href="https://github.com/Modernizr/Modernizr/blob/master/modernizr.js">source</a> or hit me up on <a href="http://twitter.com/thecssninja">twitter</a>.</p>
<p class="shorty01">Short URL: <a href="http://cssn.in/ja/033">http://cssn.in/ja/033</a></p>
<div class="clear">&nbsp;</div>
]]></content:encoded>
			<wfw:commentRss>http://www.thecssninja.com/javascript/noscope/feed</wfw:commentRss>
		<slash:comments>12</slash:comments>
		<feedburner:origLink>http://www.thecssninja.com/javascript/noscope</feedburner:origLink></item>
		<item>
		<title>Remote debugging with jsconsole, a different take</title>
		<link>http://feedproxy.google.com/~r/TheCSSNinja/~3/010wgx6h2pU/remote-debug</link>
		<comments>http://www.thecssninja.com/javascript/remote-debug#comments</comments>
		<pubDate>Mon, 07 Mar 2011 11:15:05 +0000</pubDate>
		<dc:creator>Ryan Seddon</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.thecssninja.com/?p=814</guid>
		<description><![CDATA[Ever wanted to remotely access the DOM of a mobile device so you could make changes, test ideas and generally just have a bit of fun. I know I have and I&#8217;ve been hacking to create a proof of concept piggy backed on the development of two great projects. The first is Remy Sharps awesome [...]]]></description>
			<content:encoded><![CDATA[<p>Ever wanted to remotely access the DOM of a mobile device so you could make changes, test ideas and generally just have a bit of fun. I know I have and I&#8217;ve been hacking to create a proof of concept piggy backed on the development of two great projects. The first is Remy Sharps awesome little <a href="http://jsconsole.com/">jsconsole web app</a> that lets you do a bunch of cool stuff using a simple yet elegant interface. The second is a <a href="http://browsersocket.org/">Firefox plugin</a> that allows Firefox to act as a WebSocket server and receive and delegate messages sent from a client.<span id="more-814"></span></p>
<p>Remy recently added <a href="http://www.jsconsole.com/remote-debugging.html">remote debug functionality</a> by the way of an intermediate server to delegate commands, mine works differently and the two solutions could work well together.</p>
<p>In order to use the demo you&#8217;ll need to install the <a href="https://addons.mozilla.org/en-US/firefox/addon/242722">BrowserSocket add-on</a> first.</p>
<div class="resources01"><a href="http://labs.thecssninja.com/jsconsole/" title="remote debugging example for jsconsole" class="demo">View a live demo</a> <a href="https://github.com/ryanseddon/jsconsole/archives/master" title="Download the source of the jsconsole remote debug demo" class="demo source">Download the source files</a></div>
<p>For a quick intro on what you can do, watch the screencast below. I&#8217;ll go into how it works on a technical level in the rest of the article. I&#8217;ve also filmed a super dodgy looking video of the <a href="http://vid.ly/6k1p0i">remote debugging on the iPad</a>.</p>
<p><object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0' width='609' height='375'><param name='movie' value='http://screenr.com/Content/assets/screenr_1116090935.swf' /><param name='flashvars' value='i=181264' /><param name='allowFullScreen' value='true' /><embed src='http://screenr.com/Content/assets/screenr_1116090935.swf' flashvars='i=181264' allowFullScreen='true' width='609' height='375' pluginspage='http://www.macromedia.com/go/getflashplayer'></embed></object></p>
<h2 class="subtitle02">Browser to browser connections</h2>
<p>As mentioned in the intro and screencast this requires the very clever, and awesome, <a href="http://browsersocket.org/">BrowserSocket</a> Firefox addon which allows you to let a browser window act as a WebSocket server that can be connected to by a client using the standard WebSocket API. The beauty of this is it requires very little setup and no actual server, browser to browser communication. In order to communicate with external devices they just need to be on the same local network as your current browser, you can even create an adhoc network between your computer and the device and remote debug that way.</p>
<h2 class="subtitle02">Connecting the client to the console</h2>
<p>There a two ways you can connect a client to the jsconsole webapp.</p>
<p>Using the client <a href="javascript:(function(doc) {var script = document.createElement('script');script.src = 'http://labs.thecssninja.com/jsconsole/client.js';doc.body.appendChild(script);})(this.document);" title="Drag me to your bookmarks">bookmarklet</a> you can load it on any website and connect to the generated websocket address, make sure the client and the remote device are on the same network. Once an active connection is obtained any console calls will be sent to both the client and the jsconsole webapp, all JavaScript calls will be executed on the client including loading of js libraries.</p>
<p>The second is including the JavaScript file in your project the advantage of this is you can setup automatic connections so any console calls will be sent to the web app.</p>

<div class="wp_syntax"><div class="code"><pre class="html4strict html4strict" style="font-family:monospace;"><span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">script</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;jsconsole&quot;</span> </span>
<span style="color: #009900;">    data-socketaddress<span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;ws://127.0.0.1:56187/bs/15917705/&quot;</span> </span>
<span style="color: #009900;">    <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;client.js&quot;</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">script</span>&gt;</span></pre></div></div>

<h2 class="subtitle02">How it works on a technical level</h2>
<p>Once you have installed the BrowserSocket addon in jsconsole you can call the <code>:createServer</code> command which will generate a WebSocket address that you will connect the client to.</p>
<p><img width="609" height="72" class="article-img main-img" alt="createServer command opens a BrowserSocket instance and gives you a WeSocket address to connect to" src="http://www.thecssninja.com/wp-content/uploads/2011/03/gr_createServer.png"><br />
<small style="margin: -30px 0pt 0pt; display: block;"><code>:createServer</code> command opens a BrowserSocket instance and gives you a WeSocket address to connect to</small></p>
<p>Behind the scenes the BrowserSocket addon exposes the <code>BrowserSocket()</code> constructor which uses the <a href="https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIServerSocket">nsIServerSocket interface</a> available to Firefox addons to create a socket server with the ability to accept incoming connections. </p>
<p>Using the constructor we create a new instance and supply a connection handler which will initialise the server instance and allow you to attach functions to the various events i.e. onopen/message/close etc same API as WebSockets.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> bs <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> BrowserSocket<span style="color: #009900;">&#40;</span>bsHandler<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
     bsConnection;
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> bsHandler<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">new</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        bsConnection <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>;
        bsConnection.<span style="color: #660066;">onmessage</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>msg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #006600; font-style: italic;">// Handle messages sent to browsersocket</span>
        <span style="color: #009900;">&#125;</span>
        bsConnection.<span style="color: #660066;">onopen</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #006600; font-style: italic;">// Run stuff once connection is open</span>
        <span style="color: #009900;">&#125;</span>
        bsConnection.<span style="color: #660066;">onclose</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #006600; font-style: italic;">// Revert changes once connection is closed</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>On the client side we simply use the native WebSocket API to connect to our BrowserSocket instance upon successful connection it will log a success message to both client and jsconsole webapp. Very simple and very powerful.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> ws <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> WebSocket<span style="color: #009900;">&#40;</span>url<span style="color: #009900;">&#41;</span>;
&nbsp;
ws.<span style="color: #660066;">onmessage</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>msg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #006600; font-style: italic;">// Eval code sent from jsconsole</span>
<span style="color: #009900;">&#125;</span>
ws.<span style="color: #660066;">onopen</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #006600; font-style: italic;">// Run stuff once connection is open</span>
<span style="color: #009900;">&#125;</span>
ws.<span style="color: #660066;">onclose</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #006600; font-style: italic;">// Revert changes once connection is closed</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>There is one more command called <code>:killServer</code> which does just that, kills the BrowserSocket instance and disconnects jsconsole from the client.</p>
<p><img width="609" height="72" class="article-img main-img" alt="killServer command kills the BrowserSocket instance and if there is an active connection closes that too" src="http://www.thecssninja.com/wp-content/uploads/2011/03/gr_killServer.png"><br />
<small style="margin: -30px 0pt 0pt; display: block;"><code>:killServer</code> command kills the BrowserSocket instance and if there is an active connection closes that too</small></p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;">bsConnection.<span style="color: #000066;">close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
bs.<span style="color: #000066;">stop</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;</pre></div></div>

<h2 class="subtitle02">It&#8217;s only the beginning</h2>
<p>I have many ideas that I will be implementing such as a <code>:cd</code> command so you can switch between connected device and jsconsole web app. I&#8217;ll add a roadmap/ideas wiki on my <a href="https://github.com/ryanseddon/jsconsole">github fork</a> soon. If you wish to suggest a feature create an issue for now.</p>
<p>I have also created a fork of the <a href="https://github.com/ryanseddon/BrowserSocket">BrowserSocket</a> addon on github that will eventually have some minor updates to help with remote debugging such as returning your local ip to make it easier to connect to remote devices. You can check out the <a href="https://launchpad.net/bs-ff-ext">master repository</a> on launchpad to follow the actual developments of the addon.</p>
<p class="shorty01">Short URL: <a href="http://cssn.in/ja/032">http://cssn.in/ja/032</a></p>
<div class="clear">&nbsp;</div>
]]></content:encoded>
			<wfw:commentRss>http://www.thecssninja.com/javascript/remote-debug/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://www.thecssninja.com/javascript/remote-debug</feedburner:origLink></item>
		<item>
		<title>Getting fancy with the console</title>
		<link>http://feedproxy.google.com/~r/TheCSSNinja/~3/hsegk6hKB7o/console</link>
		<comments>http://www.thecssninja.com/javascript/console#comments</comments>
		<pubDate>Wed, 23 Feb 2011 11:36:42 +0000</pubDate>
		<dc:creator>Ryan Seddon</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.thecssninja.com/?p=778</guid>
		<description><![CDATA[The trusty console.log() method serves a great functional purpose to write messages to the developer console. But did you know the console object has around twenty other methods you can use? I rarely see developers tapping into the extra power the console provides other than using it as a non-blocking alert. Let&#8217;s change that. I&#8217;ve [...]]]></description>
			<content:encoded><![CDATA[<p>The trusty <code>console.log()</code> method serves a great functional purpose to write messages to the developer console. But did you know the console object has around twenty other methods you can use? I rarely see developers tapping into the extra power the console provides other than using it as a non-blocking alert. Let&#8217;s change that.<span id="more-778"></span></p>
<p>I&#8217;ve put the following article ideas into real world practice by using <a href="http://www.modernizr.com/">Modernizr</a> as a test subject since it uses a fair amount of the concepts discussed in this article. Make sure your console is open and you&#8217;re using a good browser.</p>
<div class="resources01"><a href="http://www.thecssninja.com/demo/console/output.html" title="Modernizr example using extra console methods" class="demo" target="_blank">Demo of logging and timing</a> <a href="http://www.thecssninja.com/demo/console/test/" title="Modernizr unit tests using console.assert()" class="demo" target="_blank">Unit tests</a> <a href="http://www.thecssninja.com/demo/console/test/fail.html" title="Modernizr unit tests that will fail using console.assert()" class="demo" target="_blank">Failing unit tests</a></div>
<p>Just a side note that since I&#8217;m doing some hefty logging and using ternary statements inside some of the logs, the actual execution speed of Modernizr is affected. Always remove logs from production code.</p>
<h2 class="subtitle02">More than just messages</h2>
<p>Before we dig into the other console methods let&#8217;s show some of the powerful functionality <code>console.log()</code> has, such as the ability to pass as many arguments as you want.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> foo <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>baz<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;tubular&quot;</span><span style="color: #339933;">,</span> goo<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;rad&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> bar <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;baz&quot;</span>;
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;string&quot;</span><span style="color: #339933;">,</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span>foo.<span style="color: #660066;">goo</span><span style="color: #339933;">,</span>bar<span style="color: #339933;">,</span>foo.<span style="color: #660066;">baz</span><span style="color: #009900;">&#41;</span>; <span style="color: #006600; font-style: italic;">// string 1 rad baz tubular</span></pre></div></div>

<p>This will print out each argument and display it on the one line. That&#8217;s kinda useful but what would be better is if we could somehow intertwine all those arguments into a nicely formatted message in the console. Wait we can.</p>
<p>If you&#8217;re familiar with <a href="http://en.wikipedia.org/wiki/Printf"><code>printf()</code></a> in other languages <code>console.log()</code> shares some similarities. Taking the last example and passing in all those extra arguments we can reference them and create a nicely formatted string.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> foo <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>baz<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;tubular&quot;</span><span style="color: #339933;">,</span> goo<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;rad&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> bar <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;baz&quot;</span>;
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>
     <span style="color: #3366CC;">&quot;%s theory is %d %s concept. I can only describe it as %s and %s&quot;</span><span style="color: #339933;">,</span>
      <span style="color: #3366CC;">&quot;string&quot;</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> foo.<span style="color: #660066;">goo</span><span style="color: #339933;">,</span> bar<span style="color: #339933;">,</span> foo.<span style="color: #660066;">baz</span> 
<span style="color: #009900;">&#41;</span>;
<span style="color: #006600; font-style: italic;">// string theory is 1 rad concept. I can only describe it as baz and tubular</span></pre></div></div>

<h2 class="subtitle02">What do those %s and %d do?</h2>
<p>Glad you asked, these are special characters so we can do string formatting within our log message. Basically <code>%s</code> says print the argument as a string, <code>%d</code> says to print the argument as an integer you can also use <code>%i</code> or <code>%f</code>.</p>
<p>Each appearance of the string formatting operator will choose the corresponding argument. First replacement operator will use the first argument and so on so forth. </p>
<p>We can adjust the order in which an argument will appear within the string by using the <code>$</code> parameter preceded by the argument we wish to print.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> foo <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>baz<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;tubular&quot;</span><span style="color: #339933;">,</span> goo<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;rad&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> bar <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;baz&quot;</span>;
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>
     <span style="color: #3366CC;">&quot;%2$d theory is %d %s concept. I can only describe it as %s and %s&quot;</span><span style="color: #339933;">,</span>
     <span style="color: #3366CC;">&quot;string&quot;</span><span style="color: #339933;">,</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span>foo.<span style="color: #660066;">goo</span><span style="color: #339933;">,</span>bar<span style="color: #339933;">,</span>foo.<span style="color: #660066;">baz</span>
<span style="color: #009900;">&#41;</span>;
<span style="color: #006600; font-style: italic;">// 1 theory is 0 baz concept. I can only describe it as tubular and %s string</span></pre></div></div>

<p>What this string replacement is saying is I&#8217;ll start at the second argument and progress from there which as you can see causes an issue. </p>
<p>Essentially the first argument gets appended to the end of our arguments giving us six arguments but we only specified five locations for the strings to be replaced in and since we started at argument two it only prints four of them followed by <code>%s</code> and string.</p>
<p>We can fix this by adjusting the above log message and reset the position so everything will be printed as expected.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> foo <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>baz<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;tubular&quot;</span><span style="color: #339933;">,</span> goo<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;rad&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> bar <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;baz&quot;</span>;
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>
     <span style="color: #3366CC;">&quot;%2$d theory is %1$s %3$s concept. I can only describe it as %s and %s&quot;</span><span style="color: #339933;">,</span>
     <span style="color: #3366CC;">&quot;string&quot;</span><span style="color: #339933;">,</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span>foo.<span style="color: #660066;">goo</span><span style="color: #339933;">,</span>bar<span style="color: #339933;">,</span>foo.<span style="color: #660066;">baz</span>
<span style="color: #009900;">&#41;</span>;
<span style="color: #006600; font-style: italic;">// 1 theory is string rad concept. I can only describe it as baz and tubular</span></pre></div></div>

<p>In order to get the arguments to print out correctly we need to change the starting order of the second and third replaced items. The others are in the correct order so we don&#8217;t need to adjust where they should start looking. The string will use the arguments in this order 2,1,3,4,5.</p>
<p>String formatting is a powerful tool and I&#8217;ve only scratched the surface. Try experimenting to see what you can get it to do and take a read of some of <a href="http://www.joehewitt.com/software/firebug/docs.php">Joe Hewitts docs</a> on the console.</p>
<h2 class="subtitle02">Different kind of messages</h2>
<p>Like log there a few other methods that will allows us to present a message to the console with different styling. Those are <code>console.info()</code>, <code>console.warn()</code> and <code>console.error()</code>.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;">console.<span style="color: #660066;">info</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;%s numbers %d, %d and %d&quot;</span><span style="color: #339933;">,</span><span style="color: #3366CC;">&quot;hello&quot;</span><span style="color: #339933;">,</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span><span style="color: #CC0000;">2</span><span style="color: #339933;">,</span><span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span>; <span style="color: #006600; font-style: italic;">// hello numbers 1, 2 and 3</span>
console.<span style="color: #660066;">warn</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;%s numbers %d, %d and %d&quot;</span><span style="color: #339933;">,</span><span style="color: #3366CC;">&quot;hello&quot;</span><span style="color: #339933;">,</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span><span style="color: #CC0000;">2</span><span style="color: #339933;">,</span><span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span>;
console.<span style="color: #660066;">error</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;%s numbers %d, %d and %d&quot;</span><span style="color: #339933;">,</span><span style="color: #3366CC;">&quot;hello&quot;</span><span style="color: #339933;">,</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span><span style="color: #CC0000;">2</span><span style="color: #339933;">,</span><span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span>;</pre></div></div>

<p><img src="http://www.thecssninja.com/wp-content/uploads/2011/02/gr_info-warn-error.png" alt="Firebug example of console.info, console.warn and console.error" width="609" height="72" class="article-img main-img" /><br />
<small style="margin: -30px 0pt 0pt; display: block;">Firebug example of <code>console.info()</code>, <code>console.warn()</code> and <code>console.error()</code></small></p>
<p>All three can also use string formatting and be passed as many arguments as you want. These can obviously give you much clearer visual clues as to what is going on in your code.</p>
<h2 class="subtitle02">Logging the DOM</h2>
<p>When you log a reference to a DOM element the default behaviour is to provide a link to that DOM element with <code>console.dir()</code> and <code>console.dirxml()</code> methods we can inspect the elements properties or create a little subset of the html outline of the element.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;">console.<span style="color: #660066;">dir</span><span style="color: #009900;">&#40;</span>document.<span style="color: #660066;">documentElement</span><span style="color: #009900;">&#41;</span>;
console.<span style="color: #660066;">dirxml</span><span style="color: #009900;">&#40;</span>document.<span style="color: #660066;">documentElement</span><span style="color: #009900;">&#41;</span>;</pre></div></div>

<p><img src="http://www.thecssninja.com/wp-content/uploads/2011/02/gr_dir-dirxml.png" alt="Chrome example of console.dir and console.dirxml" width="609" height="110" class="article-img main-img" /><br />
<small style="margin: -30px 0pt 0pt; display: block;">Chrome example of <code>console.dir()</code> and <code>console.dirxml()</code></small></p>
<h2 class="subtitle02">Grouping</h2>
<p>Sometimes it would be useful to be able to group a bunch console calls for easier referencing we can do that with <code>console.group()</code>, <code>console.groupCollapsed()</code> and <code>console.groupEnd()</code>.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;">console.<span style="color: #660066;">group</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Overlord&quot;</span><span style="color: #009900;">&#41;</span>;
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Overlord stuff&quot;</span><span style="color: #009900;">&#41;</span>;
&nbsp;
console.<span style="color: #660066;">group</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Lord&quot;</span><span style="color: #009900;">&#41;</span>;
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Overlord stuff&quot;</span><span style="color: #009900;">&#41;</span>;
&nbsp;
console.<span style="color: #660066;">group</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Minion&quot;</span><span style="color: #009900;">&#41;</span>;
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Minion stuff&quot;</span><span style="color: #009900;">&#41;</span>;
console.<span style="color: #660066;">groupEnd</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
&nbsp;
console.<span style="color: #660066;">groupCollapsed</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Servant&quot;</span><span style="color: #009900;">&#41;</span>;
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Servant stuff&quot;</span><span style="color: #009900;">&#41;</span>;</pre></div></div>

<p><img src="http://www.thecssninja.com/wp-content/uploads/2011/02/gr_grouping.png" alt="Safari example of console.group and console.groupEnd" width="609" height="110" class="article-img main-img" /><br />
<small style="margin: -30px 0pt 0pt; display: block;">Safari example of <code>console.group()</code> and <code>console.groupEnd()</code></small></p>
<p>As you can see nesting <code>console.group()</code> will further nest the results, in order to end a particular group you use the <code>console.groupEnd()</code>. <code>console.groupCollapsed()</code> is the same as <code>console.group()</code> but the group and its related information will be collapsed.</p>
<h2 class="subtitle02">Code timing and profiling</h2>
<p>The console also allows you get fairly accurate timings useing <code>console.time()</code> and <code>console.timeEnd()</code>. These two methods need to be placed at the start and end of what you want to time in your code.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;">console.<span style="color: #660066;">time</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Execution time took&quot;</span><span style="color: #009900;">&#41;</span>;
<span style="color: #006600; font-style: italic;">// Some code to execute</span>
console.<span style="color: #660066;">timeEnd</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Execution time took&quot;</span><span style="color: #009900;">&#41;</span>;</pre></div></div>

<p><img src="http://www.thecssninja.com/wp-content/uploads/2011/02/gr_timing.png" alt="Firefox example of console.time and console.timeEnd" width="609" height="37" class="article-img main-img" /><br />
<small style="margin: -30px 0pt 0pt; display: block;">Firefox example of <code>console.time()</code> and <code>console.timeEnd()</code></small></p>
<p>The timers are associated with each other via their labels, this way you can have multiple timers throughout your code. When a timer hits a <code>console.timeEnd()</code> it will output a message with your label and the time it took in milliseconds to execute.</p>
<p>Along with timings we can also profile a subset of your code and output the profile stack, giving lots of juicy information about how much time the browser spent where.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;">console.<span style="color: #660066;">profile</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
<span style="color: #006600; font-style: italic;">// Some code to execute</span>
console.<span style="color: #660066;">profileEnd</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;</pre></div></div>

<h2 class="subtitle02">Asserting your code</h2>
<p>When you begin working on a complex project it&#8217;s important to start unit testing your code. This allows you to avoid simple mistakes and possible regressions. Luckily the console also includes assertions.</p>
<p>Assertions allow you to enforce rules in your code and to make sure the results it&#8217;s producing are the results you expect. The <code>console.assert()</code> method allows us to do rudimentary unit tests on our code, if something fails the console will throw an exception. The first argument can be anything, function, equality check or checking existence of an object.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> a <span style="color: #339933;">=</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> b <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;1&quot;</span>;
console.<span style="color: #660066;">assert</span><span style="color: #009900;">&#40;</span>a <span style="color: #339933;">===</span> b<span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;A doesn't equal B&quot;</span><span style="color: #009900;">&#41;</span>;</pre></div></div>

<p><img src="http://www.thecssninja.com/wp-content/uploads/2011/02/gr_assertion.png" alt="Chrome example of console.assert" width="609" height="110" class="article-img main-img" /><br />
<small style="margin: -30px 0pt 0pt; display: block;">Chrome example of <code>console.assert()</code></small></p>
<p>The assert method takes the assertion you want to enforce as the first argument, in this case a simple strict equality check, and the second argument is the message to display if it fails.</p>
<h2 class="subtitle02">Browser support</h2>
<p>Most of the following console methods discussed have quite good browser support. IE8+, Firefox with firebug, Opera or a webkit browser such as Safari or Chrome. There are a few differences between the browsers, Firefox, Safari and Chrome having the widest support. A good way of finding support is to do <code>console.dir(console)</code> which gives you nice look at the console object and it&#8217;s methods.</p>
<p>Opera with Dragonfly does support most of the methods on the console with the exception of string formatting so no fancy logging with argument re-ordering in dragonfly. There is <del datetime="2011-02-23T22:40:24+00:00">no</del> timing <ins datetime="2011-02-23T22:40:24+00:00">but no</ins> profiling (although there is profile and profileEnd available it will log saying this feature is not yet available).</p>
<p>iOS Safari also has pretty rubbish support, no <a href="#comment-2410">string formatting</a>, timing, profiling or grouping but the limited screen real estate could be the reason some of these aren&#8217;t supported. It does however support assertions.</p>
<p>IE8 has support for a pretty wide range too including string formatting and assertions but no timing, profiling, dir or dirxml.</p>
<p>Having said that using <a href="http://getfirebug.com/firebuglite">firebug lite</a> can add some of the console methods to unsupporting browsers.</p>
<p>I haven&#8217;t discussed everything available in the console but what I did cover would be the most useful features available to make debugging and testing a much smoother process. Go forth and enrich you development with more than just string logging.</p>
<p class="shorty01">Short URL: <a href="http://cssn.in/ja/031">http://cssn.in/ja/031</a></p>
<div class="clear">&nbsp;</div>
]]></content:encoded>
			<wfw:commentRss>http://www.thecssninja.com/javascript/console/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		<feedburner:origLink>http://www.thecssninja.com/javascript/console</feedburner:origLink></item>
	</channel>
</rss><!-- Dynamic page generated in 0.430 seconds. --><!-- Cached page generated by WP-Super-Cache on 2012-05-11 22:04:03 -->

