<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Think Vitamin &#187; JavaScript</title>
	<atom:link href="http://thinkvitamin.com/category/dev/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://thinkvitamin.com</link>
	<description>The Web Practitioner&#039;s Blog</description>
	<lastBuildDate>Thu, 09 Feb 2012 16:41:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>Scrolling Made Fun</title>
		<link>http://thinkvitamin.com/design/scrolling-made-fun/</link>
		<comments>http://thinkvitamin.com/design/scrolling-made-fun/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 20:00:31 +0000</pubDate>
		<dc:creator>Mat Helme</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[CSS3]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Typography]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=18304</guid>
		<description><![CDATA[Just when you thought scrolling your web page was getting boring. Scrollorama has stepped the scroll game up with this remarkable jQuery Plugin. Scrollorama allows you to manipulate text when you scroll the page. You can do everything from Transitions to Zoom to Parallax. Check out the Scrollorama site to view some great examples and [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://johnpolacek.github.com/scrollorama/"><img src="http://i.imgur.com/Ff5DF.jpg" alt="Scrollorama" /></a></p>
<p>Just when you thought scrolling your web page was getting boring. <a href="http://johnpolacek.github.com/scrollorama/">Scrollorama</a> has stepped the scroll game up with this remarkable jQuery Plugin. <a href="http://johnpolacek.github.com/scrollorama/">Scrollorama</a> allows you to manipulate text when you scroll the page. You can do everything from Transitions to Zoom to Parallax. Check out the <a href="http://johnpolacek.github.com/scrollorama/">Scrollorama</a> site to view some great examples and the plugin&#8217;s documentation.</p>
<p>This Plugin is great for landing pages and highly interactive web applications. Like CSS3 transitions, use your animations sparingly.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/design/scrolling-made-fun/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Ember.js: A More Lightweight SproutCore</title>
		<link>http://thinkvitamin.com/code/javascript/ember-js-a-more-lightweight-sproutcore/</link>
		<comments>http://thinkvitamin.com/code/javascript/ember-js-a-more-lightweight-sproutcore/#comments</comments>
		<pubDate>Wed, 14 Dec 2011 20:41:48 +0000</pubDate>
		<dc:creator>Jim Hoskins</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=17713</guid>
		<description><![CDATA[Ember.js is a new JavaScript framework that was formerly SproutCore 2.0. When I tried out SproutCore for the first time a few years ago, I was impressed with it&#8217;s data binding and templates, but I found it included a lot of things I didn&#8217;t need or want, like a large UI framework and it&#8217;s own [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.emberjs.com/">Ember.js</a> is a new JavaScript framework that was formerly SproutCore 2.0. When I tried out SproutCore for the first time a few years ago, I was impressed with it&#8217;s data binding and templates, but I found it included a lot of things I didn&#8217;t need or want, like a large UI framework and it&#8217;s own recommended toolchain and workflow. I wished I could just use the few core parts of SproutCore easily and leave out the rest. Ember.js is that wish coming true. Its main focuses are: data binding, computed properties, and auto-updating templates.</p>
<p>Check out the <a href="https://github.com/emberjs/ember.js/">Ember.js on Github</a> and read the <a href="http://yehudakatz.com/2011/12/08/announcing-amber-js/">announcement here</a>. </p>
<p><em>Ember.js had the code name Amber while in development. It was announced under the name Amber.js, but renamed to Ember.js after there was some confusion with another project</em></p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/javascript/ember-js-a-more-lightweight-sproutcore/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Creating Bookmarklets for Fun and Profit</title>
		<link>http://thinkvitamin.com/code/javascript/creating-bookmarklets-for-fun-and-profit/</link>
		<comments>http://thinkvitamin.com/code/javascript/creating-bookmarklets-for-fun-and-profit/#comments</comments>
		<pubDate>Tue, 13 Dec 2011 21:31:06 +0000</pubDate>
		<dc:creator>Jim Hoskins</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=17630</guid>
		<description><![CDATA[Bookmarklets are just like normal browser bookmarks, but when you click one, instead of taking you to another web page, it performs some action on the web page you are currently on. You have probably encountered bookmarklets in some way, whether it’s in a bookmarking service like Instapaper, or maybe a cool web design tool [...]]]></description>
			<content:encoded><![CDATA[<p>Bookmarklets are just like normal browser bookmarks, but when you click one, instead of taking you to another web page, it performs some action on the web page you are currently on.</p>
<p>You have probably encountered bookmarklets in some way, whether it’s in a bookmarking service like Instapaper, or maybe a cool web design tool that manipulates your page in some way. What you may not realize is that it’s very easy to create bookmarklets. So easy that you can use them not only in your large projects, but you can build quick bookmarklets to help you automate tedious online tasks.</p>
<p><span id="more-17630"></span></p>
<h2 id="bookmarklet_basics">Bookmarklet Basics</h2>
<p>A bookmarklet is simply a snippet of JavaScript code saved as a link.<br />
When you click the link, or click the bookmark you created from the<br />
link, it runs the JavaScript code on the page that you are currently<br />
looking at.</p>
<p>So what can you do with that? Almost anything! Let’s start, however,<br />
with a very simple example.</p>
<p>So let’s take a very simple piece of JavaScript, and create a<br />
bookmarklet.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'This is a rather simple example...'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This typical snippet of JavaScript simply pops up a box that says “This<br />
is a rather simple example…”</p>
<p>So let’s now create a link that executes this snippet.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;a</span> <span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;javascript:alert('This is a rather simple example...');&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span> Show Alert <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/a<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>So it looks kind of like a typical <code>&lt;a&gt;</code> tag. The href however is a<br />
little different. Instead of a typical page url, it is our JavaScript<br />
code, preceded by <code>javascript:</code>. This is what allows us to run our code.</p>
<p>If you click the link, you will get the popup. But if you drag the link<br />
to your bookmarks toolbar, you will then be able to click that bookmark,<br />
and execute the code on any page.</p>
<h2 id="interacting_with_the_page">Interacting with the Page.</h2>
<p>The previous example isn’t very useful, it just pops up the same old<br />
message each time. The beauty of a bookmarklet is that it runs the code<br />
<strong><em>within</em></strong> the page you are viewing. This means your bookmarklet’s<br />
code has access to all of the page elements, variables, and functions on<br />
that page. This is also the reason to be careful using 3rd party<br />
bookmarklets, they can also do malicious things like retrieve your<br />
cookie from the page you are on and transmit it elsewhere.</p>
<p>Let’s jazz up our example to popup the title of the current page.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;a</span> <span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;javascript:alert('This page is : ' + document.title);&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span> Show Title <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/a<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Now this link and bookmarklet will tell us the title of the current<br />
page. This is because the <code>document</code> will be the page document of the<br />
current page.</p>
<p>We can do much more than just get information and pop it up in an alert,<br />
we can apply styles to a page, add or remove elements, or even<br />
manipulate forms to automate data entry.</p>
<p>If you have some long form that is tedious to fill out, but the<br />
actions you want to take can be automated, bookmarklets can save you a lot<br />
of time. Better yet, you can create a bookmarklet for a coworker and be a<br />
hero who saved him or her hours of work by simply spending a few minutes<br />
creating a bookmarklet to help.</p>
<p>If you are making a bookmarklet to work on a particular site, there is a<br />
good chance that the site uses jQuery (it’s that popular). If it’s another<br />
framework you could utilize that too. If you know jQuery is on the page<br />
you are using your bookmarklet for, it makes building bookmarklets that<br />
much easier.</p>
<p>Here is a simple example. Sometimes when confronted with dozens of checkboxes on a page, I want to<br />
just check them all, and maybe uncheck the few that don’t apply to me.<br />
If there is no “Check All” button, I have to do it myself.<br />
The code for that is simple, assuming you have jQuery on the target<br />
page.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">':checkbox'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">attr</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'checked'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This selects all checkboxes, and checks them all. Just throw code in a<br />
link, drag the link to you bookmarks bar, and you’re ready to go<br />
checkbox crazy at a moment’s notice.</p>
<h2 id="workflow">Workflow</h2>
<p>Often when creating bookmarklets, the code requires some<br />
experimentation, and several JavaScript statements.</p>
<p>Here is the workflow I use.</p>
<h3 id="step_1_experiment_in_the_dev_tools_or_firebug">Step 1: Experiment in the Dev Tools or Firebug</h3>
<p>Since your code will run on a page, pick out a target page, and open<br />
the JavaScript console of your Dev Tools, or Firebug. This allows you to<br />
experiment with the JavaScript code and what CSS selectors can be used to select elements (if<br />
you are using a framework like jQuery, as shown above).</p>
<p>You may want to write the code snippet in a text editor, then copy and<br />
paste it into the console, rather than try to form you statement(s) in<br />
the console itself.</p>
<p>Once your code does what you want, move to step 2.</p>
<h3 id="step_2_prepare_your_code">Step 2: Prepare Your Code</h3>
<p>Since you will have to place your code in the <code>href</code> attribute of an<br />
<code>&lt;a&gt;</code> tag, there are some formatting restrictions. First take note of<br />
any quotes in your code. I like to use only single quotes in my<br />
bookmarklet code, so when I wrap the code in double quotes to embed it<br />
in the HTML, I don’t break out of the <code>href</code> value.</p>
<p>Your code should also be compact. You can do this fairly easily by<br />
removing line breaks. Make sure you are using semicolons properly, but<br />
you already do that, right? You could also try using a JavaScript<br />
minifier to reduce the code, but if there is that much code, you may<br />
want to try a different technique, I will explain shortly.</p>
<h3 id="step_3_create_the_bookmarklet">Step 3: Create the Bookmarklet</h3>
<p>There are two main ways to add a bookmarklet to your browser. You can<br />
create an <code>&lt;a&gt;</code> tag on a page, and drag it to your bookmarks, or you can<br />
create a normal bookmark to any page, then edit its title and link. You<br />
would then set the like location to your ‘javascript: …’ code. This<br />
strategy can be a bit cumbersome, but editing an existing bookmark is<br />
the way you have to do it on iOS.</p>
<p>I prefer to create a link on an HTML page. This makes it easier to<br />
share.</p>
<p>We saw the syntax for this at the beginning of this article.</p>
<p>It’s an <code>&lt;a&gt;</code> tag. The <code>href</code> is in the format <code>"javascript: YOUR CODE<br />
 HERE"</code> and the content of the tag will be the title of the bookmarklet.</p>
<p>You can either create a new HTML page to create this link, or you can<br />
 use something like <a href="http://jsfiddle.net/">jsFiddle</a> to quickly create<br />
 your link. This has the added benefit of making it easy to share with a<br />
 coworker, a friend, or the world.</p>
<h2 id="bigger_bookmarklets">Bigger Bookmarklets</h2>
<p>If you are creating a bookmarklet that goes beyond a simple gimmick or<br />
 time saver, you may have a lot more code. While you can cram quite a bit<br />
 of code in that link, it’s often better to instead create a JavaScript<br />
 file that is hosted on the web, then have the bookmarklet load that<br />
 script into the page. Your script will execute in the page just as it<br />
 would have with the shorter bookmarklets.</p>
<p>Creating an external file has the added benefit of being able to update<br />
 the logic of the bookmarklet by simply updating the target file.</p>
<p>The readable version of the code looks like this.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#40;</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: #003366; font-weight: bold;">var</span> script <span style="color: #339933;">=</span> document.<span style="color: #660066;">createElement</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'SCRIPT'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  script.<span style="color: #660066;">src</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">'http://example.com/the_code.js'</span><span style="color: #339933;">;</span>
  document.<span style="color: #660066;">body</span>.<span style="color: #660066;">appendChild</span><span style="color: #009900;">&#40;</span>script<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>This creates a <code>&lt;script&gt;</code> tag, sets its <code>src</code>, and adds it to the page,<br />
which will fetch and run the file immediately. Of course you would<br />
change the value of <code>src</code> to be the url to your JavaScript file.</p>
<p>The whole thing is wrapped in a function that will execute immediately.<br />
This is because we are creating a variable called <code>script</code>. Since we are<br />
going to be running this on another page, we don’t want to accidentally<br />
mess up a global variable that page may be counting on. By wrapping it<br />
in this self executing function, we keep all our variables to ourselves,<br />
not messing up the target JavaScript environment.</p>
<p>Ultimately the code is compressed to this:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;a</span> <span style="color: #000066;">href</span>=<span style="color: #ff0000;">&quot;javascript:(function(){var script=document.createElement('SCRIPT');script.src='http://example.com/the_code.js';document.body.appendChild(script);})()&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span> Do Something! <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/a<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<h2 id="use_your_new_superpowers_for_good">Use Your New Superpowers for Good</h2>
<p>Now that you can make bookmarklets, you can add all sorts of features to<br />
any site you want. You are now a developer for any site on the web.</p>
<p>Almost anything is possible when you can run JavaScript on a website. If<br />
you want to learn about what is possible with JavaScript, check out the<br />
JavaScript and jQuery lessons on<br />
<a href="http://teamtreehouse.com?cid=193">Treehouse</a>.</p>
<h2> Update: A real-life example</h2>
<p>I was watching the iOS videos on <a href="http://teamtreehouse.com?cid=193">Treehouse</a>, and coding along when I realized what I would like is for the video to pause when I tab over to Xcode, then resume when I come back to Treehouse. Since I work for Treehouse I could have easily added it to the feature development list, but I wanted it right away. So a bookmarklet was born. </p>
<p><a href="http://jsfiddle.net/jimrhoskins/Ybnv6/3/">You can check out the bookmarklet here</a>. The code was built for use on a <a href="http://teamtreehouse.com?cid=193">Treehouse</a> video page, but it should work on any page with HTML5 video and jQuery.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/javascript/creating-bookmarklets-for-fun-and-profit/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Organize Your Code with RequireJS</title>
		<link>http://thinkvitamin.com/code/javascript/organize-your-code-with-requirejs/</link>
		<comments>http://thinkvitamin.com/code/javascript/organize-your-code-with-requirejs/#comments</comments>
		<pubDate>Tue, 27 Sep 2011 21:38:32 +0000</pubDate>
		<dc:creator>Jim Hoskins</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=16498</guid>
		<description><![CDATA[Writing web applications using JavaScript, HTML, and CSS can become overwhelming quickly. Between managing UI, data, interactions, and network requests, application code can become a real mess, and this isn&#8217;t helped by the way the browser loads JavaScript code. In most other programming environments, there is some way to split your code into modules or [...]]]></description>
			<content:encoded><![CDATA[<p>Writing web applications using JavaScript, HTML, and CSS can become<br />
overwhelming quickly. Between managing UI, data, interactions, and<br />
network requests, application code can become a real mess, and this<br />
isn&#8217;t helped by the way the browser loads JavaScript code.</p>
<p><span id="more-16498"></span></p>
<p>In most other programming environments, there is some way to split your<br />
code into modules or scripts, and specifically require one module from<br />
another.</p>
<p>In JavaScript, we can split our code into multiple files, but there is<br />
no way to declare in one script that you are depending on another. Worse<br />
yet, the place where scripts are loaded isn&#8217;t even in the same language<br />
you are writing your code. You load all your JavaScript dependencies<br />
from your HTML document, not your JavaScript files. That may work for<br />
including a little Ajax here, and an animation there, but for large<br />
single page applications, this does not cut it.</p>
<p>I have had the opportunity to work on a large single page application<br />
for Treehouse, and tried using <a href="http://requirejs.org/">RequireJS</a>, and I love it. </p>
<p>How does <a href="http://requirejs.org/">RequireJS</a> make building an application easier?</p>
<h2 id="module_definition">Module Definition</h2>
<p>All of your code is written in self contained modules. Modules are small<br />
chunks of your application that serve a specific purpose. How much code<br />
you define in a module is left up to you. You could write your whole app<br />
in one module, but that would be defeating the organizational benefit,<br />
and the ability to extract or replace portions of your app easily.</p>
<p>A typical simple module is defined like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">define<span style="color: #009900;">&#40;</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>
&nbsp;
  <span style="color: #003366; font-weight: bold;">function</span> method <span style="color: #009900;">&#40;</span>x<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">return</span> x <span style="color: #339933;">+</span> x<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#123;</span>
    someValue<span style="color: #339933;">:</span> <span style="color: #3366CC;">'foobar'</span><span style="color: #339933;">,</span>
    myMethod<span style="color: #339933;">:</span> method
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Here we use the <code>define()</code> function to define our function. In this<br />
example we passed in a function which will return our module. In this<br />
case our module is an object with two properties: a string <code>someValue</code><br />
and a function <code>myMethod</code>.</p>
<p>This code would make up the entirety of our JavaScript file for this<br />
module. Nothing should be declared outside of a single <code>define</code> call.</p>
<p>If this code was saved in <code>my/utils.js</code>, this module would be defined<br />
as the module &#8220;my/utils&#8221;.</p>
<h2 id="module_dependencies">Module Dependencies.</h2>
<p>Defining modules is great, but we are going to need to use parts of<br />
modules from other modules. When we define a module, we can pass a list<br />
of module names, and RequireJS will make sure to retrieve these modules<br />
before your module is executed, and it will pass those modules as<br />
parameters of the definition function.</p>
<p>Given we still have our &#8220;my/utils&#8221; module, and another module<br />
&#8220;models/Person&#8221;, which defines a single JavaScript class Person, here is<br />
how we might define a module that requires both of them.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">define<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span><span style="color: #3366CC;">&quot;models/Person&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;my/utils&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>Person<span style="color: #339933;">,</span> utils<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> people <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
  people.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">new</span> Person<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Jim'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  people.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">new</span> Person<span style="color: #009900;">&#40;</span>utils.<span style="color: #660066;">someValue</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#123;</span>people<span style="color: #339933;">:</span> people<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Here we defined a module that we will say lives in &#8220;app/people.js&#8221;. It<br />
required two modules, &#8220;models/Person&#8221;, and &#8220;my/utils&#8221;. These modules<br />
were then passed to our module definition function, and we bound them to<br />
the parameters Person and utils. We could call the parameters anything<br />
at all, but I chose to reflect the module names.</p>
<p>In this example, I capitalized the Person module, since in this hypothetical module it is returning a JavaScript class, not a normal object with properties, so I used a capitalized name as a convention.</p>
<p>The module then defined a people array, added a couple of Persons to it,<br />
and exposed it as a property of its own module.</p>
<p>RequireJS looks at the dependencies of all the modules in your<br />
application, and will fetch and execute all of the modules in the<br />
proper order so that each module has exactly what it needs to run.</p>
<h2 id="running_the_app">Running the App</h2>
<p>Now we have our modules defined, we want to use them to actually start<br />
an application. This will usually be done in some sort of &#8220;main&#8221; file,<br />
which isn&#8217;t really a module.</p>
<p>Instead of using <code>define()</code> to wrap our code, in our main file we use<br />
<code>require()</code>. The <code>require()</code> function is similar, in that you pass it an<br />
optional array of dependencies, and a function which will be executed<br />
when those dependencies are resolved. However this code is not stored as<br />
a named module, as its purpose is to be run immediately, much like the<br />
main() function in a C program.</p>
<p>So let us say our main file is in &#8220;/scripts/main.js&#8221;, and let&#8217;s also say<br />
that our modules were also defined under &#8220;/scripts/&#8221;. So really &#8220;my/utils&#8221;<br />
lives in &#8220;/scripts/my/utils.js&#8221;, and &#8220;models/Person&#8221; lives in<br />
&#8220;/scripts/models/Person.js&#8221;, and so on. We will see how this is important later.<br />
But our main.js might look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">require<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span><span style="color: #3366CC;">&quot;app/people&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>people<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>people.<span style="color: #660066;">people</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Here, we just required the &#8220;app/people module&#8221;, and bound it to people.<br />
The people module exposed a people property, which we alerted the first<br />
element of.</p>
<p>So now we need to include the JavaScript in our HTML page. We do it all<br />
with one script tag.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;script</span> <span style="color: #000066;">data-main</span>=<span style="color: #ff0000;">&quot;scripts/main&quot;</span> <span style="color: #000066;">src</span>=<span style="color: #ff0000;">&quot;scripts/require.js&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/script<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Our actual file structure looks like this</p>
<ul>
<li>root/
<ul>
<li>index.html</li>
<li>scripts/</li>
<li>require.js</li>
<li>main.js</li>
<li>app/
<ul>
<li>people.js</li>
</ul>
</li>
<li>models/
<ul>
<li>Person.js</li>
</ul>
</li>
<li>my/
<ul>
<li>utils.js</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>Our script tag is including via the src attribute the require.js script<br />
from the scripts directory. We also defined an attribute callded<br />
data-main, with the name of our main application module &#8220;scripts/main&#8221;.<br />
This means RequireJS will load up &#8220;/scripts/main.js&#8221; as the main entry<br />
point. </p>
<p>It also sets the root directory for modules to the &#8220;/scripts/&#8221;<br />
directory. This is why we can call a module &#8220;my/utils&#8221; when it really<br />
lives in &#8220;/scripts/my/utils.js&#8221;. You can require a module from an<br />
absolute location by giving its name using a leading &#8220;./&#8221; or &#8220;/&#8221; or a<br />
full URL. Otherwise it assumes the module lives relative to the main<br />
script.</p>
<h2 id="optimizing">Optimizing</h2>
<p>While having code split into multiple files is great for organization,<br />
it&#8217;s terrible for performance. That is why RequireJS includes an<br />
optimizer which will take the modules of your app, move them into a<br />
single file, and minify them, to improve performance.</p>
<h2 id="bonus_requirejs_dojo_awesome">Bonus: RequireJS + Dojo = Awesome!</h2>
<p>My application uses <a href="http://dojotoolkit.org/">Dojo</a>, and the entire UI is built programatically<br />
using custom Dojo Widgets. It turns out Dojo&#8217;s loader is compatible with<br />
RequireJS,<a href="http://requirejs.org/docs/dojo.html"> if you set your application up right</a>. This made my<br />
application so much easier to develop and maintain. </p>
<p>Also, using <a href="http://jashkenas.github.com/coffee-script/">CoffeeScript</a> to extend Dojo Widgets is also amazing, but<br />
that&#8217;s another post!</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/javascript/organize-your-code-with-requirejs/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>The Little Book on CoffeeScript</title>
		<link>http://thinkvitamin.com/code/the-little-book-on-coffeescript/</link>
		<comments>http://thinkvitamin.com/code/the-little-book-on-coffeescript/#comments</comments>
		<pubDate>Wed, 20 Jul 2011 20:10:58 +0000</pubDate>
		<dc:creator>Alan Johnson</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=15069</guid>
		<description><![CDATA[Have you heard about CoffeeScript? It&#8217;s an awesome language that helps smooth out some of JavaScript&#8217;s rough corners, and since CoffeeScript compiles into JavaScript you can use it anywhere you&#8217;d normally use JavaScript, like in the browser or on servers using Node.js. I&#8217;ve been doing a ton of scripting with CoffeeScript for different small system [...]]]></description>
			<content:encoded><![CDATA[<p>Have you heard about <a href="http://jashkenas.github.com/coffee-script/">CoffeeScript</a>? It&#8217;s an awesome language that helps smooth out some of JavaScript&#8217;s rough corners, and since CoffeeScript compiles into JavaScript you can use it anywhere you&#8217;d normally use JavaScript, like in the browser or on servers using Node.js. I&#8217;ve been doing a ton of scripting with CoffeeScript for different small system maintenance tasks and have just started working on using it instead of JavaScript for a few different projects and have really enjoyed it.</p>
<p>The guys at <a href="http://arcturo.com">Arcturo</a> recently released an eBook written by <a href="http://alexmaccaw.co.uk/">Alex MacCaw</a> about CoffeeScript, called <a href="http://arcturo.github.com/library/coffeescript/index.html">The Little Book on CoffeeScript</a>, that helps you dive into programming with CoffeeScript. It&#8217;s a great, quick read, and I&#8217;d highly recommend it if you&#8217;re interested in figuring out what CoffeeScript is all about and how you might use it.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/the-little-book-on-coffeescript/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Build Dynamic Pages with Knockout.js</title>
		<link>http://thinkvitamin.com/code/javascript/build-dynamic-pages-with-knockout-js/</link>
		<comments>http://thinkvitamin.com/code/javascript/build-dynamic-pages-with-knockout-js/#comments</comments>
		<pubDate>Tue, 14 Jun 2011 15:20:26 +0000</pubDate>
		<dc:creator>Jim Hoskins</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=14381</guid>
		<description><![CDATA[<p>Building dynamic web pages using JavaScript can be a complex task. Fortunately, frameworks like jQuery, MooTools, and others make it much easier to interact with the browser. However DOM frameworks only solve part of the problem.</p>

<p>When building an application that has a lot of data that can be updated, and any piece of information could be represented in several places on the page, it becomes a pain to try to make sure the interface accurately represents the data at any point in time.</p>]]></description>
			<content:encoded><![CDATA[<p>Building dynamic web pages using JavaScript can be a complex task. Fortunately, frameworks like jQuery, MooTools, and others make it much easier to interact with the browser. However DOM frameworks only solve part of the problem.</p>
<p>When building an application that has a lot of data that can be updated, and any piece of information could be represented in several places on the page, it becomes a pain to try to make sure the interface accurately represents the data at any point in time. <span id="more-14381"></span></p>
<p>There are heavy duty application frameworks that can take care of this problem like <a href="http://www.sproutcore.com/">SproutCore</a>, <a href="http://cappuccino.org/">Cappuccino</a>, and <a href="http://www.sencha.com/">ExtJS</a>. These tools have a steep learning curve, and can be inconvenient to integrate into an existing project. </p>
<p>Lightweight tools like <a href="http://documentcloud.github.com/backbone/">Backbone</a> and <a href="http://maccman.github.com/spine/">Spine</a> offer solutions that are easier to pick up. You can watch my Master Class on <a href="http://membership.thinkvitamin.com/library/html5-mobile-web-applications">creating an application with Backbone.js and jQuery Mobile on Think Vitamin Membership</a>.</p>
<h2 id="the_mvc_solution">The MVC Solution</h2>
<p>All of these tools utilize a similar pattern for solving the data consistency problem, Model-View-Controller or MVC.<br />
Put simply you write some JavaScript to represent your data (Model), some JavaScript to store and handle changes to that data (Controller), and some JavaScript to render the HTML representation of the data (View). All in all, it turns out to be a lot of code to write.</p>
<h2 id="the_mvvc_solution">The MVVC Solution</h2>
<p><a href="http://knockoutjs.com/">Knockout.js</a> offers a different pattern: MVVC, or Model-View-ViewController. In Knockout you still create a Model in JavaScript to represent your data. The View, however, is written in HTML, utilizing HTML5 data attributes to define metadata. Then a ViewController defines what data is presented to the View.</p>
<p>Let&#8217;s take a look at a very simple example.</p>
<p>HTML:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">My name is 
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;span</span> <span style="color: #000066;">data-bind</span>=<span style="color: #ff0000;">&quot;text: name&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span><span style="color: #000000; font-weight: bold;">&lt;/span<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>JavaScript:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> viewController <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066;">name</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Jim&quot;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
ko.<span style="color: #660066;">applyBindings</span><span style="color: #009900;">&#40;</span>viewController<span style="color: #009900;">&#41;</span></pre></div></div>

<p><a href="http://jsfiddle.net/jimrhoskins/GCscS/2/">Run this code</a></p>
<p>In this example we create a View in HTML. We give the span a <code>data-bind</code> attribute specifying its text contents should be determined by <code>name</code>.</p>
<p>In the JavaScript we create a simple ViewController as a normal JavaScript Object, and define that <code>name</code> should have the value <code>"Jim"</code>. In this example the string <code>"Jim"</code> is a Model, though a Model could be a more complex object.</p>
<p>When we call <code>ko.applyBindings()</code> and pass it the <code>viewController</code>. Knockout wires up the View (HTML) to the ViewController (JavaScript), and ensures that it sets the <code>text</code> of our span to the value of <code>name</code> in the ViewController.</p>
<h2 id="observables">Observables</h2>
<p>Our first example showed how Knockout can do a simple static text substitution, but what would happen if we called the JavaScript code <code>viewController.name = "Nick";</code> ?</p>
<p>The ViewController would have an updated Model, but our HTML View would not change to reflect the name. This is because there is no way for Knockout to directly be notified that the data in the ViewController has changed.</p>
<p>Knockout provides a special object called an Observable that solves this problem. An observable wraps a value, or Model, and when you change its value, Knockout notifies all Views (and other code interested in that value) that it has changed. This way our View can update itself with the new value.</p>
<p>Let&#8217;s look at an example of how to use an Observable</p>
<p>HTML:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">My name is 
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;span</span> <span style="color: #000066;">data-bind</span>=<span style="color: #ff0000;">&quot;text: name&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span><span style="color: #000000; font-weight: bold;">&lt;/span<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>JavaScript:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> viewController <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066;">name</span><span style="color: #339933;">:</span> ko.<span style="color: #660066;">observable</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Jim&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
setTimeout<span style="color: #009900;">&#40;</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>
  viewController.<span style="color: #000066;">name</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Nick&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">2000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
ko.<span style="color: #660066;">applyBindings</span><span style="color: #009900;">&#40;</span>viewController<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><a href="http://jsfiddle.net/jimrhoskins/5xSNW/2/">Run this code</a></p>
<p>The View Code is the same. However, in the <code>viewController</code> object, instead of assigning a string to the key <code>name</code>, we instead use <code>ko.observable("Jim")</code>. This is how we create an Observable object. When we create it, we can pass an optional initial value, in this example <code>"Jim"</code>.</p>
<p>To access and change the value of an observable object, we need to treat it as a function. If we were to call <code>viewController.name()</code>, it would return the current name. To set the value, we pass it a new value <code>viewController.name("Nick")</code>. This will change the value, and notify the View that it has changed.</p>
<p>In this example, we set a timeout so that in 2 seconds, we will update the <code>viewController.name</code>, and the view is updated automatically to display &#8220;Nick&#8221;.</p>
<h2 id="bindings">Bindings</h2>
<p>So how does the View know to watch the <code>name</code> value, and how does it know what to do when it changes?</p>
<p>The View uses bindings, which are defined in the <code>data-bind</code> attribute of an HTML element. The syntax is similar to JSON, and takes the form <code>key: value, key: value</code>. A key is a type of binding, of which there are many built in; <code>text</code>: represents the text content of a tag, <code>value</code>: the value of a form input, etc&#8230; You can view the different available bindings at the documentation.</p>
<p>The value of a binding is either a literal JavaScript value, like a string or number, or it can be an expression. If the expression is the name of an key in the ViewController, knockout will determine which Observable is used to determine the value, and will watch it for changes. When the Observable signals it has changed, Knockout evaluates the current value, and updates the view.</p>
<h2 id="there8217s_more">There&#8217;s More</h2>
<p>This first part only scratches the surface of what Knockout is capable of doing. In upcoming posts I&#8217;ll show you how to create dependent observables, and create more advanced interfaces with Knockout.</p>
<p>Knockout is a great tool to keep in your toolbox because it solves a common problem in a different way than most other tools.</p>
<p>At first I was wary of Knockout, because I worried that I would be adding too much logic to my Views (HTML). But working with it, it actually has made the code easier to maintain, since I can reason about how pieces of the views are generated by just looking at it, instead of having to read all of the JavaScript code to see what may be manipulating it.</p>
<p>I hope you give Knockout a try!</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/javascript/build-dynamic-pages-with-knockout-js/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Run Linux in your browser</title>
		<link>http://thinkvitamin.com/code/javascript/run-linux-in-your-browser/</link>
		<comments>http://thinkvitamin.com/code/javascript/run-linux-in-your-browser/#comments</comments>
		<pubDate>Mon, 23 May 2011 10:48:05 +0000</pubDate>
		<dc:creator>Ryan Carson</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=14016</guid>
		<description><![CDATA[I came across this on Hacker News and it blew my mind. Fabrice Bellard just created a PC emulator that boots Linux, written in JavaScript. It even works on my iPad. From the technical notes &#8230; The PC emulator is written in Javascript. The emulated hardware consists in the following devices: 32 bit x86 compatible [...]]]></description>
			<content:encoded><![CDATA[<p><img src="https://img.skitch.com/20110523-kynuhqcxhdqc6jycr2phrgeneu.jpg" alt="Screenshot of a PC emulator running Linux" /></p>
<p>I came across this on Hacker News and it blew my mind. <a href="http://bellard.org/">Fabrice Bellard</a> just created a <a href="http://bellard.org/jslinux/">PC emulator that boots Linux</a>, written in JavaScript. It even works on my iPad.</p>
<p>From the technical notes &#8230;</p>
<p>The PC emulator is written in Javascript. The emulated hardware consists in the following devices:</p>
<ul>
<li>32 bit x86 compatible CPU</li>
<li>8259 Programmble Interrupt Controller</li>
<li>8254 Programmble Interrupt Timer</li>
<li>16450 UART</li>
<li>Real Time Clock.</li>
</ul>
<p>The code is written in pure Javascript using the <a href="http://www.khronos.org/registry/typedarray/specs/latest/">W3C Typed Arrays</a>. A slightly slower fallback mode is implemented for browsers missing this support. For the exact list of supported browsers, see the <a href="http://bellard.org/jslinux/faq.html">FAQ</a>.</p>
<p>It&#8217;s officially supported by</p>
<ul>
<li>Firefox 4.x</li>
<li>Chrome 11</li>
<li>Opera 11.11</li>
<li>Internet Explorer 9</li>
</ul>
<p>Hot damn.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/javascript/run-linux-in-your-browser/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>cdn js</title>
		<link>http://thinkvitamin.com/code/javascript/cdn-js/</link>
		<comments>http://thinkvitamin.com/code/javascript/cdn-js/#comments</comments>
		<pubDate>Tue, 10 May 2011 13:54:40 +0000</pubDate>
		<dc:creator>Alan Johnson</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=13735</guid>
		<description><![CDATA[Everyone loves the Google CDN right? Even Microsoft runs their own CDN. The problem is, they only host the most popular libraries. We host the other stuff. cdn js is a relatively new, free JavaScript CDN based on Amazon CloudFront and Amazon Route53. Can&#8217;t find a CDN for an open source JavaScript library you&#8217;re using? [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>Everyone loves the Google CDN right? Even Microsoft runs their own CDN. The problem is, they only host the most popular libraries. We host the other stuff.</p></blockquote>
<p><a href="http://cdnjs.com/">cdn js</a> is a relatively new, free JavaScript CDN based on Amazon CloudFront and Amazon Route53. Can&#8217;t find a CDN for an open source JavaScript library you&#8217;re using? Just upload it to cdn js and your problem&#8217;s solved.</p>
<p>I would love to see all of the major JavaScript CDN players join forces so that everyone could benefit from cached libraries and faster load times.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/javascript/cdn-js/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Google Traceur</title>
		<link>http://thinkvitamin.com/code/javascript/google-traceur/</link>
		<comments>http://thinkvitamin.com/code/javascript/google-traceur/#comments</comments>
		<pubDate>Mon, 09 May 2011 13:46:40 +0000</pubDate>
		<dc:creator>Alan Johnson</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=13614</guid>
		<description><![CDATA[Google Traceur is a new JavaScript library by Google that implements proposed next generation JavaScript language features, like classes, inheritance, and composition, and makes them available to developers today. It does so by converting code written for Traceur into JavaScript code that runs in today&#8217;s browsers. I&#8217;ve been reading up on CoffeeScript a lot lately, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://code.google.com/p/traceur-compiler/">Google Traceur</a> is a new JavaScript library by Google that implements proposed next generation JavaScript language features, like classes, inheritance, and composition, and makes them available to developers today. It does so by converting code written for Traceur into JavaScript code that runs in today&#8217;s browsers.</p>
<p>I&#8217;ve been reading up on <a href="http://jashkenas.github.com/coffee-script/">CoffeeScript</a> a lot lately, and it seems like CoffeeScript handles quite a few of the same language problems, but with a new syntax rather than just extending JavaScript.</p>
<p>Both languages are really exciting to me because of the prospects for having a little more language flexibility in the browser. I can&#8217;t wait to see where this trend takes us.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/javascript/google-traceur/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Actual JavaScript Engine Performance</title>
		<link>http://thinkvitamin.com/code/actual-javascript-engine-performance/</link>
		<comments>http://thinkvitamin.com/code/actual-javascript-engine-performance/#comments</comments>
		<pubDate>Mon, 02 May 2011 13:10:59 +0000</pubDate>
		<dc:creator>Alan Johnson</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=13588</guid>
		<description><![CDATA[This page on Actual JavaScript Engine Performance by Douglas Crockford is really interesting. For bonus points, read the JSMeter paper Douglas links to. It&#8217;s absolutely true that we should be testing real application performance rather than benchmarking made up scenarios, and it&#8217;s good to see some performance data from JSLint. I think I&#8217;m mainly impressed [...]]]></description>
			<content:encoded><![CDATA[<p>This page on <a href="http://crockford.com/javascript/performance.html">Actual JavaScript Engine Performance</a> by Douglas Crockford is really interesting. For bonus points, read the <a href="http://research.microsoft.com/pubs/118663/paper_tr.pdf">JSMeter</a> paper Douglas links to. It&#8217;s absolutely true that we should be testing real application performance rather than benchmarking made up scenarios, and it&#8217;s good to see some performance data from JSLint.</p>
<p>I think I&#8217;m mainly impressed to see that <em>all</em> of the JavaScript engines are ridiculously fast these days. Hats off to the IE team for being the best browser on that list. I certainly wouldn&#8217;t have expected to see that a couple of years ago.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/actual-javascript-engine-performance/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Handlebars.js Part 3: Tips and Tricks</title>
		<link>http://thinkvitamin.com/code/handlebars-js-part-3-tips-and-tricks/</link>
		<comments>http://thinkvitamin.com/code/handlebars-js-part-3-tips-and-tricks/#comments</comments>
		<pubDate>Wed, 13 Apr 2011 12:54:58 +0000</pubDate>
		<dc:creator>Alan Johnson</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[HTML and XHTML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=13351</guid>
		<description><![CDATA[So we&#8217;re about done learning about Handlebars.js, but I&#8217;ve got a few examples of tricks I&#8217;ve found while using Handlebars that I figured I would share. If you haven&#8217;t read them yet, I&#8217;d highly recommend reading Part 1 and Part 2 of the series on Handlebars before you dive into this post. The debug Helper [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://thinkvitamin.com/wp-content/uploads/2011/03/handlebars.png" alt="" title="handlebars" class="alignnone size-full wp-image-12905" /></p>
<p>So we&#8217;re about done learning about Handlebars.js, but I&#8217;ve got a few examples of tricks I&#8217;ve found while using Handlebars that I figured I would share. If you haven&#8217;t read them yet, I&#8217;d highly recommend reading <a href="http://thinkvitamin.com/code/getting-started-with-handlebars-js/">Part 1</a> and <a href="http://thinkvitamin.com/code/handlebars-js-part-2-partials-and-helpers/">Part 2</a> of the series on Handlebars before you dive into this post.<br />
<span id="more-13351"></span></p>
<h3>The <code>debug</code> Helper</h3>
<p>It can be easy at times to get confused about where you are in the stack in a Handlebars.js template. I usually keep a <code>debug</code> helper around to help me figure that out.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">Handlebars.<span style="color: #660066;">registerHelper</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;debug&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>optionalValue<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Current Context&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;====================&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>optionalValue<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Value&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;====================&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>optionalValue<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>You could then use that helper in any template like:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#123;</span>debug<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>or like:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#123;</span>debug someValue<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>and you&#8217;ll see output in the JavaScript console letting you know what&#8217;s going on:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">Current Context
====================
email: &quot;alan@test.com&quot;
first_name: &quot;Alan&quot;
last_name: &quot;Johnson&quot;
member_since: &quot;Mar 25, 2011&quot;
phone: &quot;1234567890&quot;
stripeClass: &quot;even&quot;
__proto__: Object
Value
====================
Alan</pre></td></tr></table></div>

<h3>A jQuery Plugin</h3>
<p>It tends to be a pretty regular pattern with Handlebars to compile a template, process it with some data, and then fill a DOM element with the results. Here&#8217;s a quick jQuery plugin that does all of that for you:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;What's Up?&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id=&quot;content&quot;&gt;
      This is where the content goes!
    &lt;/div&gt;
    &lt;script id=&quot;template&quot; type=&quot;text/handlebars&quot;&gt;
      Hello, {{name}}!
    &lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;jquery.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;handlebars-0.9.0.pre.5.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
      (function($) {
        var compiled = {};
        $.fn.handlebars = function(template, data) {
          if (template instanceof jQuery) {
            template = $(template).html();
          }
&nbsp;
          compiled[template] = Handlebars.compile(template);
          this.html(compiled[template](data));
        };
      })(jQuery);
&nbsp;
      $('#content').handlebars($('#template'), { name: &quot;Alan&quot; });
    &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre></td></tr></table></div>

<h3>Updating More Than Just The Template Area</h3>
<p>A lot of dynamic applications tend to have a layout that generally stays the same regardless of the template you&#8217;re displaying, and then a content area that shows the template that you&#8217;re looking at. Maybe there&#8217;s a sidebar with some navigation in it that generally stays the same, but each time you update the main content area you also need to update the title on the page. It&#8217;s pretty easy to cheat a bit with Handlebars to make that work. Handlebars helpers are allowed to not return anything, in which case they won&#8217;t add anything to the template output. You can use a helper that doesn&#8217;t return anything to update other parts of the page!</p>
<p>Imagine a site that has a structure something like this:</p>
<p><img src="http://thinkvitamin.com/wp-content/uploads/2011/04/Untitleddrawing.png" alt="Sample App Layout" title="Sample App Layout" width="705" height="529" class="alignnone size-full wp-image-13354" /></p>
<p>And maybe the markup looks like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;body&gt;
  &lt;h1&gt;Title&lt;/h1&gt;
  &lt;div id=&quot;nav-sidebar&quot;&gt;
    &lt;ul&gt;
      &lt;li&gt;Links&lt;/li&gt;
      &lt;li&gt;Go&lt;/li&gt;
      &lt;li&gt;Here&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/div&gt;
  &lt;div id=&quot;content&quot;&gt;
  	Content goes here!
  &lt;/div&gt;
&lt;/body&gt;</pre></td></tr></table></div>

<p>Here&#8217;s a quick helper that will let you update the <code>h1</code> for the title each time you apply content to the main content area:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">Handlebars.<span style="color: #660066;">registerHelper</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;title&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>fn<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'h1'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">html</span><span style="color: #009900;">&#40;</span>fn<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>And finally, a template that uses the helper:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">  {{#title}}Details for {{name}}{{/title}}
&nbsp;
  &lt;div class=&quot;user-details&quot;&gt;
    ...user details template stuff goes here...
  &lt;/div&gt;</pre></td></tr></table></div>

<p>When the template above is run, it will call the title helper, but since the title helper just returns an empty string, it won&#8217;t add anything to the template output. It will, though, use jQuery to update the <code>h1</code> element for the page&#8217;s title.</p>
<h3>Wrapping Up</h3>
<p>I think this about wraps up the series on Handlebars.js. It&#8217;s been fun to share Handlebars.js with everyone, and to hear about the apps you&#8217;re writing with Handlebars.js. Please let me know in the comments if there&#8217;s anything else relating to Handlebars.js that you&#8217;d be interested in hearing about, or if you have any questions.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/handlebars-js-part-3-tips-and-tricks/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Have you seen requestAnimationFrame?</title>
		<link>http://thinkvitamin.com/code/have-you-seen-requestanimationframe/</link>
		<comments>http://thinkvitamin.com/code/have-you-seen-requestanimationframe/#comments</comments>
		<pubDate>Fri, 08 Apr 2011 01:00:51 +0000</pubDate>
		<dc:creator>Alan Johnson</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[HTML and XHTML]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=13283</guid>
		<description><![CDATA[CSS3 Animations make a huge impact on reducing CPU and making animation more efficient in the browser, but I don&#8217;t think we&#8217;ll ever get away from sometimes having to use JavaScript to do animations. requestAnimationFrame is a neat new draft spec that a lot of the browsers are starting to support in nighty builds. It [...]]]></description>
			<content:encoded><![CDATA[<p>CSS3 Animations make a huge impact on reducing CPU and making animation more efficient in the browser, but I don&#8217;t think we&#8217;ll ever get away from sometimes having to use JavaScript to do animations.</p>
<p><a href="http://webstuff.nfshost.com/anim-timing/Overview.html">requestAnimationFrame</a> is a neat new draft spec that a lot of the browsers are starting to support in nighty builds. It basically sets up a global animation run loop for your entire page. It&#8217;s really useful for reducing CPU usage when doing JavaScript based animations because it allows the browser to only redraw once after all of the registered animation callbacks have been called, rather than after each individual callback. It also allows the browser to throttle the number of animation callbacks that are called for tabs in the background.</p>
<p>There are a ton more details about requestAnimationFrame on <a href="http://paulirish.com/2011/requestanimationframe-for-smart-animating/">Paul Irish&#8217;s blog</a>, including how to wire it up for browsers that don&#8217;t support it yet so that you can start writing JavaScript animations that use requestAnimationFrame now.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/have-you-seen-requestanimationframe/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Handlebars.js Part 2: Partials and Helpers</title>
		<link>http://thinkvitamin.com/code/handlebars-js-part-2-partials-and-helpers/</link>
		<comments>http://thinkvitamin.com/code/handlebars-js-part-2-partials-and-helpers/#comments</comments>
		<pubDate>Fri, 01 Apr 2011 16:11:33 +0000</pubDate>
		<dc:creator>Alan Johnson</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[HTML and XHTML]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=13206</guid>
		<description><![CDATA[Last week we looked at the basics of using Handlebars.js. We learned how to write a basic template to loop over a list of people. This week we&#8217;ll build on that by learning about using Handlebars&#8217; built-in helpers, writing and using partials, and writing custom helpers. Let&#8217;s get started! Built-In Helpers Handlebars includes a few [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://thinkvitamin.com/wp-content/uploads/2011/03/handlebars.png" alt="" title="handlebars" class="alignnone size-full wp-image-12905" /></p>
<p>Last week we looked at the basics of <a href="http://thinkvitamin.com/code/getting-started-with-handlebars-js/">using Handlebars.js</a>. We learned how to write a basic template to loop over a list of people. This week we&#8217;ll build on that by learning about using Handlebars&#8217; built-in helpers, writing and using partials, and writing custom helpers. Let&#8217;s get started!</p>
<p><span id="more-13206"></span></p>
<h3>Built-In Helpers</h3>
<p>Handlebars includes a few built in helpers that make life easier. They are <code>{{#each}}</code>, <code>{{#if}}</code>, and {{#unless}}.</p>
<h4>The <em>each</em> Helper</h4>
<p>The <code>{{#each}}</code> helper iterates over each item in an array. Here&#8217;s an example.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;script id=&quot;each-template&quot; type=&quot;text/x-handlebars-template&quot;&gt;
  {{#each people}}
    ... output person's info here...
  {{/each}}
&lt;/script&gt;</pre></td></tr></table></div>

<p>The above template would iterate over each item in the array named people and output the content of the block.</p>
<h4>The <em>if</em> Helper</h4>
<p>The <code>{{#if}}</code> helper does just what you&#8217;d expect. It allows you to implement an if block in your code. The <code>if</code> helper outputs the block that it contains if the value given to it is truthy.</p>
<p>One tricky aspect of the helper, though, is that Handlebars doesn&#8217;t support conditional statements, so code like <code>{{#if x > y}}</code> isn&#8217;t possible. That&#8217;s on purpose. Our take is that any tricky logic like that can be wrapped up into a helper to make sure that your template stays nice and clean.</p>
<p>Here&#8217;s an example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;script id=&quot;each-template&quot; type=&quot;text/x-handlebars-template&quot;&gt;
  {{#if people}}
    ... output person's info here...
  {{/if}}
&lt;/script&gt;</pre></td></tr></table></div>

<p>That template would only output the inside of the block if people was truthy, so it wouldn&#8217;t output if people was <code>null</code>, <code>0</code>, <code>false</code>, or <code>undefined</code>. Probably a more appropriate if statement in the above example would be <code>{{#if people.length}}</code>, so that the block would also not be displayed if a people array is present, but empty.</p>
<h4>The <em>unless</em> Helper</h4>
<p>The <code>{{#unless}}</code> helper is basically just the opposite of if. It only outputs the contained block if the given expression is false. So, for example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;script id=&quot;each-template&quot; type=&quot;text/x-handlebars-template&quot;&gt;
  {{#unless people.length}}
    There aren't any people.
  {{/unless}}
&lt;/script&gt;</pre></td></tr></table></div>

<p>The above template would only output the sentence <em>There aren&#8217;t any people</em> if <code>people.length</code> evaluates to a falsy value like <code>null</code>, <code>0</code>, <code>false</code>, or <code>undefined</code>.</p>
<h4>The <em>else</em> Expression</h4>
<p>Handlebars.js includes a special expression, <code>{{else}}</code>, that can be used with any block helper to represent what should be output if the given expression evaluates to a falsy value. Here&#8217;s an example of how to use it:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;script id=&quot;each-template&quot; type=&quot;text/x-handlebars-template&quot;&gt;
  {{#if people.length}}
    ... output person's info here...
  {{else}}
    There aren't any people.
  {{/if}}
&lt;/script&gt;</pre></td></tr></table></div>

<h3>Partials</h3>
<p>Partials come in handy when you have a chunk of a Handlebars.js template that you need to use in a few different contexts. The <code>Handlebars.registerPartial</code> method registers a partial. It takes the name of the partial as its first argument and either a template source string or a compiled template as its second argument. The fact that it accepts a compiled template as the second argument is actually pretty useful. That allows you, for example, to use the partial in a loop that outputs a list but also append items to the list later using the partial&#8217;s template function.</p>
<p>To use a partial from a template, simply include <code>{{> partialName}}</code>. Here&#8217;s an example of using a partial:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;script id=&quot;people-template&quot; type=&quot;text/x-handlebars-template&quot;&gt;
  {{#each people}}
    {{&gt; person}}
  {{/each}}
&lt;/script&gt;
&nbsp;
&lt;script id=&quot;person-partial&quot; type=&quot;text/x-handlebars-template&quot;&gt;
  &lt;div class=&quot;person&quot;&gt;
    &lt;h2&gt;{{first_name}} {{last_name}}&lt;/h2&gt;
    &lt;div class=&quot;phone&quot;&gt;{{phone}}&lt;/div&gt;
    &lt;div class=&quot;email&quot;&gt;&lt;a href=&quot;mailto:{{email}}&quot;&gt;{{email}}&lt;/a&gt;&lt;/div&gt;
    &lt;div class=&quot;since&quot;&gt;User since {{member_since}}&lt;/div&gt;
  &lt;/div&gt;
&lt;/script&gt;
&nbsp;
&lt;script type=&quot;text/javascript&quot;&gt;
  $(document).ready(function() {
    var template = Handlebars.compile($(&quot;#people-template&quot;).html());
    Handlebars.registerPartial(&quot;person&quot;, $(&quot;#person-partial&quot;).html());
&nbsp;
    template(yourData);
  }
&lt;/script&gt;</pre></td></tr></table></div>

<h3>Writing Customer Helpers</h3>
<p>One of our major motivations in writing Handlebars.js rather than just using <a href="https://github.com/janl/mustache.js">mustache.js</a> was to allow users to define global helpers. Handlebars supports defining both expression and block helpers.</p>
<h4>Custom Expression Helpers</h4>
<p>To register an expression helper, use the <code>Handlebars.registerHelper</code> method. It takes the name of the helper and the helper function as arguments. Handlebars.js takes whatever is returned from the helper function and writes it out to the template, so be sure to always return a string from your custom helpers.</p>
<p>To write an expression helper function to output a formatted phone number, you could define the following helper:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">Handlebars.<span style="color: #660066;">registerHelper</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;formatPhoneNumber&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>phoneNumber<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  phoneNumber <span style="color: #339933;">=</span> phoneNumber.<span style="color: #660066;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #3366CC;">&quot;(&quot;</span> <span style="color: #339933;">+</span> phoneNumber.<span style="color: #660066;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #339933;">,</span><span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;) &quot;</span> <span style="color: #339933;">+</span> phoneNumber.<span style="color: #660066;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">3</span><span style="color: #339933;">,</span><span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;-&quot;</span> <span style="color: #339933;">+</span> phoneNumber.<span style="color: #660066;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">6</span><span style="color: #339933;">,</span><span style="color: #CC0000;">4</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>You would use the <code>formatPhoneNumber</code> helper in a template like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">{{formatPhoneNumber phoneNumber}}</pre></td></tr></table></div>

<h4>Custom Block Helpers</h4>
<p>Custom block helpers are also registered with the <code>Handlebars.registerHelper</code> method. When a helper is used with a block, Handlebars will pass the contents of the block compiled into a function to the helper. If an <code>{{else}}</code> expression is found in the block Handlebars will also pass the contents of the <code>else</code> block to the helper as well.</p>
<p>Here&#8217;s an example block helper that iterates through an array, letting the contents know whether it&#8217;s an even or odd row. The helper takes the array to iterate over, the css class name for even rows, and the css class name for odd rows as arguments. You&#8217;ll also notice the compiled template function <code>fn</code> for the contents of the block and the compiled else block function, <code>elseFn</code> are arguments to the helper function. The helper simply adds a property named <code>stripeClass</code> to each item in the array as we iterate over it so that we can output that class name within the block. If the array given is falsy or empty the helper just returns the contents of the else block.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">Handlebars.<span style="color: #660066;">registerHelper</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;stripes&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>array<span style="color: #339933;">,</span> even<span style="color: #339933;">,</span> odd<span style="color: #339933;">,</span> fn<span style="color: #339933;">,</span> elseFn<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>array <span style="color: #339933;">&amp;&amp;</span> array.<span style="color: #660066;">length</span> <span style="color: #339933;">&gt;</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> buffer <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> j <span style="color: #339933;">=</span> array.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> j<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #003366; font-weight: bold;">var</span> <span style="color: #000066; font-weight: bold;">item</span> <span style="color: #339933;">=</span> array<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #006600; font-style: italic;">// we'll just put the appropriate stripe class name onto the item for now</span>
      <span style="color: #000066; font-weight: bold;">item</span>.<span style="color: #660066;">stripeClass</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">%</span> <span style="color: #CC0000;">2</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">0</span> <span style="color: #339933;">?</span> even <span style="color: #339933;">:</span> odd<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #006600; font-style: italic;">// show the inside of the block</span>
      buffer <span style="color: #339933;">+=</span> fn<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// return the finished buffer</span>
    <span style="color: #000066; font-weight: bold;">return</span> buffer<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">return</span> elseFn<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>You would use the stripes helper in your template like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#123;</span>#stripes myArray <span style="color: #3366CC;">&quot;even&quot;</span> <span style="color: #3366CC;">&quot;odd&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span>
  <span style="color: #339933;">&lt;</span>div <span style="color: #003366; font-weight: bold;">class</span><span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;{{stripeClass}}&quot;</span><span style="color: #339933;">&gt;</span>
    ... <span style="color: #660066;">code</span> <span style="color: #000066; font-weight: bold;">for</span> the row ...
  <span style="color: #339933;">&lt;/</span>div<span style="color: #339933;">&gt;</span>
<span style="color: #009900;">&#123;</span><span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">else</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span>
  <span style="color: #339933;">&lt;</span>em<span style="color: #339933;">&gt;</span>There aren<span style="color: #3366CC;">'t any people.&lt;/em&gt;
{{/stripes}}</span></pre></td></tr></table></div>

<h3>See It In Action</h3>
<p>I actually wrote up a quick sample project that uses all of the techniques I&#8217;ve describe here. You can check that code out on <a href="https://github.com/commondream/handlebars-helpers-examples">GitHub</a> or download a <a href="https://github.com/commondream/handlebars-helpers-examples/zipball/helpers">zip file of the source</a>.</p>
<h3>There&#8217;s More!</h3>
<p>There&#8217;s a lot going on with Handlebars.js helpers, so we&#8217;ve got at least one more article worth of content to cover. Next week I&#8217;ll show you how to do some neat tricks with the internals of how Handlebars.js blocks work. Please feel free to email me at <a href="mailto:alan@carsonified.com">alan@carsonified.com</a> if you have any questions and I can cover those as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/handlebars-js-part-2-partials-and-helpers/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Getting Started with Handlebars.js</title>
		<link>http://thinkvitamin.com/code/getting-started-with-handlebars-js/</link>
		<comments>http://thinkvitamin.com/code/getting-started-with-handlebars-js/#comments</comments>
		<pubDate>Fri, 25 Mar 2011 13:11:42 +0000</pubDate>
		<dc:creator>Alan Johnson</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[HTML and XHTML]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=12866</guid>
		<description><![CDATA[Web apps are using JavaScript to create dynamic interfaces now more than ever before, and that&#8217;s not a trend that will change any time soon. DOM manipulation is great for simpler JavaScript apps, but what do you do when you&#8217;re changing huge chunks of the document with each change of the view? That&#8217;s where JavaScript [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://thinkvitamin.com/wp-content/uploads/2011/03/handlebars.png" alt="" title="handlebars" class="alignnone size-full wp-image-12905" /></p>
<p>Web apps are using JavaScript to create dynamic interfaces now more than ever before, and that&#8217;s not a trend that will change any time soon. DOM manipulation is great for simpler JavaScript apps, but what do you do when you&#8217;re changing huge chunks of the document with each change of the view? That&#8217;s where JavaScript templating comes into play.</p>
<p>There are quite a few amazing JavaScript templating libraries available. I started out with JavaScript templating using <a href="https://github.com/janl/mustache.js">mustache.js</a>, a JavaScript port of the excellent <a href="http://mustache.github.com/">Mustache</a> templating language and moved on to a stint using John Resig&#8217;s <a href="http://ejohn.org/blog/javascript-micro-templating/">JavaScript Micro-Templating</a>. jQuery has its official <a href="http://api.jquery.com/category/plugins/templates/">templating plugin</a>, and <a href="http://documentcloud.github.com/underscore/#template">so does Underscore.js</a>. Even 37signals has a JavaScript templating language, although it&#8217;s for CoffeeScript, called <a href="https://github.com/sstephenson/eco">eco</a>. My personal favorite JavaScript templating language these days is <a href="http://handlebars.strobeapp.com/">Handlebars.js</a>.</p>
<p><span id="more-12866"></span></p>
<h3>Why handlebars.js?</h3>
<p>I have to disclose that I&#8217;m a little biased &#8211; I worked with Yehuda Katz on Handlebars.js. We wrote Handlebars because we loved Mustache&#8217;s approach to &#8220;logic-less templating&#8221; in general but had a rough time dealing with the hoops you had to jump through to use global helpers and the lack of support for accessing variables further up the template&#8217;s call stack. We also really wanted templates that could be precompiled instead of having to be compiled on the client and really wanted to write the fastest templating language possible. Although we didn&#8217;t end up with the absolute fastest templating framework for JavaScript, Handlebars.js is lightning fast and accomplished our other goals.</p>
<h3>Installation and Usage</h3>
<p>The easiest way to install Handlebars.js is to <a href="https://github.com/wycats/handlebars.js/downloads">download the latest build</a> from the GitHub project. We&#8217;re not quite to a 1.0 release yet, but Handlebars.js is being actively used by quite a few projects. Handlebars is just a JavaScript library, so you include it in your pages the same way you would any other script:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;script type=&quot;text/javascript&quot; 
    src=&quot;/scripts/handlebars-0.9.0.pre.4.js&quot; /&gt;</pre></td></tr></table></div>

<p>For basic templating, you may want to just include your template inline in the document. You can use a script tag with a custom type to hold it:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;script id=&quot;some-template&quot; type=&quot;text/x-handlebars-template&quot;&gt;
  &lt;table&gt;
    &lt;thead&gt;
      &lt;th&gt;Username&lt;/th&gt;
      &lt;th&gt;Real Name&lt;/th&gt;
      &lt;th&gt;Email&lt;/th&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
      {{#users}}
        &lt;tr&gt;
          &lt;td&gt;{{username}}&lt;/td&gt;
          &lt;td&gt;{{firstName}} {{lastName}}&lt;/td&gt;
          &lt;td&gt;{{email}}&lt;/td&gt;
        &lt;/tr&gt;
      {{/users}}
    &lt;/tbody&gt;
  &lt;/table&gt;
&lt;/script&gt;</pre></td></tr></table></div>

<p>Then you can compile, process, and display that template with the following code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">  <span style="color: #003366; font-weight: bold;">var</span> source   <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#some-template&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">html</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #003366; font-weight: bold;">var</span> template <span style="color: #339933;">=</span> Handlebars.<span style="color: #660066;">compile</span><span style="color: #009900;">&#40;</span>source<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #003366; font-weight: bold;">var</span> data <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> users<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span>
      <span style="color: #009900;">&#123;</span>username<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;alan&quot;</span><span style="color: #339933;">,</span> firstName<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Alan&quot;</span><span style="color: #339933;">,</span> lastName<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Johnson&quot;</span><span style="color: #339933;">,</span> email<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;alan@test.com&quot;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
      <span style="color: #009900;">&#123;</span>username<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;allison&quot;</span><span style="color: #339933;">,</span> firstName<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Allison&quot;</span><span style="color: #339933;">,</span> lastName<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;House&quot;</span><span style="color: #339933;">,</span> email<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;allison@test.com&quot;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
      <span style="color: #009900;">&#123;</span>username<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;ryan&quot;</span><span style="color: #339933;">,</span> firstName<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Ryan&quot;</span><span style="color: #339933;">,</span> lastName<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Carson&quot;</span><span style="color: #339933;">,</span> email<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;ryan@test.com&quot;</span> <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#93;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
  $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#content-placeholder&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">html</span><span style="color: #009900;">&#40;</span>template<span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>I&#8217;m using jQuery for inserting the template output above, but Handlebars will work with any framework that  you&#8217;d like to use it with. One thing to note is that Handlebars always compiles templates into a JavaScript function. That makes them super easy to work with.</p>
<h3>Basic Expressions</h3>
<p>The simplest dynamic element in a Handlebars template is an expression. An expression is surrounded by handlebars, like <code>{{expression}}</code>. When an expression is reached in the template, Handlebars will look for an item in the current context that matches the expression given. If the matching item is a value, the value is output. If the matching item is a function, the function is called. If no matching item is found, nothing is written to the output. Expressions support using the dot (<code>.</code>) operator in expressions to output nested values. For example, <code>{{user.firstName}}</code> would output the firstName property on the user value in the current context.</p>
<p>By default Handlebars escapes the results of expressions, but using a &#8220;triple-stash&#8221;, like <code>{{{expression}}}</code>, will cause the expression to be output unescaped.</p>
<h3>Blocks</h3>
<p>Sometimes it&#8217;s helpful to focus your work on a particular expression within a template. That&#8217;s where blocks come in. Blocks are represented in Handlebars with the pound (<code>#</code>) symbol followed by an expression. Blocks end with a closing mustache, <code>{{/expression}}</code>.</p>
<p>If the expression given evaluates to an Array, Handlebars will iterate over each item in the Array, setting the current context to that item.  Here&#8217;s an example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> data <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> people<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span>
    <span style="color: #009900;">&#123;</span><span style="color: #000066;">name</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Alan&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 
    <span style="color: #009900;">&#123;</span><span style="color: #000066;">name</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Allison&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 
    <span style="color: #009900;">&#123;</span><span style="color: #000066;">name</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Ryan&quot;</span><span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> group<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Bloggers&quot;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;script type=&quot;text/x-handlebars-template&quot;&gt;
  &lt;ul&gt;
    {{#people}}
      &lt;li&gt;{{name}}&lt;/li&gt;
    {{/people}}
  &lt;/ul&gt;
&lt;/script&gt;</pre></td></tr></table></div>

<p>Because blocks change the current expression context, Handlebars supports using the <code>../</code> expression to access parent contexts. So in the previous example, we could have used the expression <code>../group</code> while iterating over each of the people to print out the name of the group:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;script type=&quot;text/x-handlebars-template&quot;&gt;
  &lt;ul&gt;
    {{#people}}
      &lt;li&gt;{{name}} - {{../group}}&lt;/li&gt;
    {{/people}}
  &lt;/ul&gt;
&lt;/script&gt;</pre></td></tr></table></div>

<p>If a block&#8217;s expression evaluates to anything other than an Array, Handlebars simply sets the context to the result of evaluating the expression. This can save a lot of typing when outputting several properties of an object:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> data <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> person<span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span> 
    firstName<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Alan&quot;</span><span style="color: #339933;">,</span> 
    lastName<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Johnson&quot;</span><span style="color: #339933;">,</span> 
    email<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;alan@test.com&quot;</span><span style="color: #339933;">,</span> 
    phone<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;123-456-7890&quot;</span> 
  <span style="color: #009900;">&#125;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;script type=&quot;text/x-handlebars-template&quot;&gt;
  {{#person}}
    &lt;div&gt;Name: {{firstName}} {{lastName}}&lt;/div&gt;
    &lt;div&gt;Email: {{email}}&lt;/div&gt;
    &lt;div&gt;Phone: {{phone}}&lt;/div&gt;
  {{/person}}
&lt;/script&gt;</pre></td></tr></table></div>

<h3>What&#8217;s Next?</h3>
<p>There&#8217;s a ton more to cover, so I&#8217;ll be posting about advanced Handlebars.js techniques next week. We&#8217;ll talk about partials, block helpers, global helpers, and how to precompile your templates so that they don&#8217;t have to be compiled on the client.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/getting-started-with-handlebars-js/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Encrypting Cookies in the Browser</title>
		<link>http://thinkvitamin.com/code/encrypting-cookies-in-the-browser/</link>
		<comments>http://thinkvitamin.com/code/encrypting-cookies-in-the-browser/#comments</comments>
		<pubDate>Mon, 14 Feb 2011 09:00:41 +0000</pubDate>
		<dc:creator>James Robson</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=11745</guid>
		<description><![CDATA[Cookies are a convenient, often necessary way to maintain state and data in web applications. Since this is well known, cookies are a target and potential vulnerability you have to be aware of when developing for the web. There are various ways to go about improving cookie security. In this article we&#8217;ll discuss an additional [...]]]></description>
			<content:encoded><![CDATA[<p>Cookies are a convenient, often necessary way to maintain state and data in web applications. Since this is well known, cookies are a target and potential vulnerability you have to be aware of when developing for the web.</p>
<p>There are various ways to go about <a href="http://thinkvitamin.com/code/how-to-create-totally-secure-cookies/">improving cookie security</a>. In this article we&#8217;ll discuss an additional method, client-side encryption.<span id="more-11745"></span></p>
<h3>Attacks on cookies</h3>
<p>Cookies are stored locally on a computer, usually in clear text. If a computer is accessed by multiple people, one person might scan another&#8217;s cookie folder and look for things like passwords or long-life session IDs.</p>
<p><img src="http://thinkvitamin.com/wp-content/uploads/2011/01/figure1.png" alt="" /></p>
<p>Cookies are generally set server-side using the &#8216;Set-Cookie&#8217; HTTP header and sent to the client. This makes them a target for network sniffing. You can use SSL/TLS to prevent this by encrypting the network packets, but many sites, such as Facebook, only use HTTPS during login, and then switch to standard unencrypted HTTP for ensuing requests. Tools like <a href="http://codebutler.com/firesheep">FireSheep</a> make sniffing and hijacking session cookies (just another cookie!) trivial in certain conditions.</p>
<p>Another common attack, cross-site scripting (Xss for short), is when some client-side code, usually JavaScript, is <a href="http://nakedsecurity.sophos.com/2010/09/21/twitter-onmouseover-security-flaw-widely-exploited/">injected into a web page</a> and executed without the user&#8217;s knowledge. When JavaScript runs in this context, it may, among other things, access user cookies. This vulnerability is especially difficult to prevent, since users are at the mercy of the websites they visit. You can only hope that site Y has taken the necessary precautions to prevent Xss injection. The only sure way for you to prevent cross-site scripting is to turn off JavaScript altogether.</p>
<h3>Encrypting cookies in your browser</h3>
<p>My company, <a href="http://completelyprivatefiles.com/">CompletelyPrivateFiles.com</a>, provides encryption solutions for the web. As part of our infrastructure we&#8217;ve built a JavaScript API that encrypts cookies with 256-bit AES encryption on the client, that is, in the browser. The API is available for free. You can find out more <a href="http://www.completelyprivatefiles.com/api/1.1/cookie/docs/">here</a>.</p>
<p>The API works by combining a random, dynamically assigned &#8216;seed-key&#8217; with a generally weaker user or application secret (like a password) to generate a strong 256-bit key. It then uses that key to encrypt and decrypt cookies on the client. It&#8217;s a very minimal, unobtrusive API by design, and should easily integrate with preexisting applications and frameworks.</p>
<p><img src="http://thinkvitamin.com/wp-content/uploads/2011/01/figure2.png" alt="" /></p>
<p>You&#8217;ll need an API account so your application can obtain the seed key from our servers. After sign-up you&#8217;ll be given a &#8216;sub-token&#8217; which you include in your pages. To get started with the API add our JavaScript library to your page.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script type<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;text/javascript&quot;</span>
src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;http://www.completelyprivatefiles.com/api/1.1/cookie/encrypt.js&quot;</span><span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>Then, paste in the following code, replacing __YOUR_SUB_TOKEN__ with the sub-token you get from sign-up.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script type<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;text/javascript&quot;</span><span style="color: #339933;">&gt;</span>document.<span style="color: #000066; font-weight: bold;">write</span><span style="color: #009900;">&#40;</span>ssxdom<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'__YOUR_SUB_TOKEN__'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>Now, you&#8217;re ready to read and write encrypted cookies. To save an encrypted cookie to disk make the following call.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">setSecureCookie<span style="color: #009900;">&#40;</span>secret<span style="color: #339933;">,</span> cookieName<span style="color: #339933;">,</span> cookieVal<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>The &#8216;secret&#8217; parameter is determined by your application. You may require the user to enter the secret. Or, you could generate it automatically from internal application values like username, timestamp, etc. You could even provide a truly random, i.e. actual, encryption key for &#8216;secret&#8217;. It&#8217;s entirely based on the security/convenience trade-off you decide on.</p>
<p>To decrypt and access the cookie value, make the following function call. Note that &#8216;secret&#8217; in this call must be the same &#8216;secret&#8217; used in setSecureCookie().</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> cookieVal <span style="color: #339933;">=</span> getSecureCookie<span style="color: #009900;">&#40;</span>secret<span style="color: #339933;">,</span> cookieName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<h3>Cookie security</h3>
<p>Consider the vulnerability scenarios outlined at the beginning of this article. In each case, the exploit only mattered the moment the attacker obtained the cookie&#8217;s value. With encrypted cookies, accessing the cookie does not mean accessing it&#8217;s value.</p>
<p>In the case where someone gains local access to a computer and scans for cookies, encrypted cookies prevent the attacker from viewing the cookie contents.</p>
<p>Let&#8217;s say you encrypt cookies and send them in their encrypted form to the server for storage. The server can later use &#8216;Set-Cookie&#8217; and the cookie remains encrypted until it reaches your client. A hijacking attack is mitigated in this case, even if the cookies are sent over clear HTTP.</p>
<p>Xss exploits are more difficult to stop since the attacker may have full access to the page and its dynamic elements. If the attack is specific enough, it might simply access variables in memory. In the case where an Xss exploit accesses your cookies, however, the same protections as above apply. The encryption must be circumvented first.</p>
<p>It should be noted that encryption doesn&#8217;t prevent a malicious user or process from damaging cookie values and making them impossible to decrypt. This would put your application in an inconsistent state, but the value of the cookies themselves won&#8217;t have been compromised.</p>
<h3>User privacy</h3>
<p>In addition to improving security, you can also use encrypted cookies to enhance user privacy. As more and more user data lives &#8216;in the cloud&#8217;, and concerns about privacy become more and more prominent, you may want to make assurances to the user that some, or perhaps all, of their data is known only to them.</p>
<p>One way this might be accomplished is to prompt the user for an additional secret after they&#8217;ve logged in, and use that to store sensitive information in an encrypted cookie. The problem with cookies, however, is that they expire. By storing them server-side in their encrypted form, and using the &#8216;Set-Cookie&#8217; header, you can easily persist secret client-side data for longer, even indefinite periods.</p>
<p>An example of this would be an online check register where the transactions are stored online, but the actual bank account data is accessed through an encrypted cookie. By storing the cookie on the server and decrypting it locally, the bank information can be used within the context of the application yet remain private to the user.</p>
<h3>Summary</h3>
<p>Encrypting cookies on the client provides an additional level of security not just for the obvious reason, that it encrypts sensitive information before storage. It gives you another way in which to design security into your application. It&#8217;s not just a tool for security, either, but also a tool for privacy, both of which are important issues in modern web programming.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/encrypting-cookies-in-the-browser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Impact JavaScript Game Engine</title>
		<link>http://thinkvitamin.com/code/javascript/impact-javascript-game-engine/</link>
		<comments>http://thinkvitamin.com/code/javascript/impact-javascript-game-engine/#comments</comments>
		<pubDate>Tue, 08 Feb 2011 16:48:55 +0000</pubDate>
		<dc:creator>Alan Johnson</dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=11912</guid>
		<description><![CDATA[I&#8217;m constantly blown away by how many types of software that have traditionally only been possible to write either natively or using plugins like Flash can now be written for the web with HTML5 technologies. Lately I&#8217;ve been really impressed with Impact, a framework for developing 2D games on the canvas. It has some really helpful and [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m constantly blown away by how many types of software that have traditionally only been possible to write either natively or using plugins like Flash can now be written for the web with HTML5 technologies. Lately I&#8217;ve been really impressed with <a href="http://impactjs.com">Impact</a>, a framework for developing 2D games on the canvas. It has some really helpful and well documented classes for working with sound, animations, and input including touch input on mobile devices, and works in all of the browsers that support the canvas, including IE9. There&#8217;s even a bundled browser-based editor!</p>
<p><img src="http://thinkvitamin.com/wp-content/uploads/2011/02/ImpactScreenshot.png" alt="Impact works in all modern browsers, including IE9" /></p>
<p>Even if you&#8217;re not interested in writing a game yourself, be sure to check out the Impact demo game, <a href="http://playbiolab.com/">BioLab Disaster</a>. It&#8217;s amazing to see what they&#8217;re doing with just HTML5 technologies. I have to warn you, though, that Impact comes with a price tag. Impact licenses cost $99 per developer. If you&#8217;d prefer open source solutions instead, here&#8217;s a <a href="http://www.reddit.com/r/javascript/comments/f094j/list_of_js_game_engines_community_effort/">great list of JavaScript game engines</a> on Reddit. I&#8217;m really curious to know if developers are willing to pay for JavaScript libraries, especially when those libraries are taking on more difficult to write code like graphics in the canvas, audio, and timing in games.</p>
<p>Paid libraries or not, it&#8217;s clear that writing really rich applications directly in the browser without the use of flash or other plugins is here to stay. I can&#8217;t wait to see what kinds of neat apps our community creates next.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/javascript/impact-javascript-game-engine/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Tips on Learning JavaScript</title>
		<link>http://thinkvitamin.com/code/tips-on-learning-javascript/</link>
		<comments>http://thinkvitamin.com/code/tips-on-learning-javascript/#comments</comments>
		<pubDate>Mon, 07 Feb 2011 09:00:20 +0000</pubDate>
		<dc:creator>Andy Walpole</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=11649</guid>
		<description><![CDATA[In his seminal article Style Versus Design Jeffrey Zeldman wrote The web used to look like a phone book . What he should have written is: The web used to look like a phone book sitting in a tacky 70s disco. Thanks to the combined garishness of animated GIFs, Java applets and JavaScript, many web [...]]]></description>
			<content:encoded><![CDATA[<p>In his seminal article <a href="http://www.adobe.com/designcenter/dialogbox/stylevsdesign/">Style Versus Design</a> Jeffrey Zeldman wrote The web used to look like a phone book . What he should have written is: The web used to look like a phone book sitting in a tacky 70s disco. Thanks to the combined garishness of animated GIFs, Java applets and JavaScript, many web pages were distinctly vulgar.</p>
<p>Fast forward to 2011 and animated GIFs and Java applets have been thrown into the dustbin of history; but, surprisingly, JavaScript has enjoyed a renaissance of epic proportions. So much so that you can&#8217;t call yourself a web designer today without some knowledge of JavaScript under your belt.<span id="more-11649"></span></p>
<p>This state of affairs has come about through a number of different reasons. The introduction of AJAX as a means of updating web pages without a manual refresh, much more powerful browsers that can cope with a large amounts of scripting and the widespread use of JavaScript libraries such as jQuery, Dojo and Mootools.</p>
<p>At the beginning of last year I placed learning JavaScript on My Things To Do In 2010 list. A year later, I&#8217;ve made substantial progress. I would now classify my skills as intermediate. And with every new website I create, I learn more.</p>
<p>Below are some tips that you may find of use if you too are considering learning JavaScript.</p>
<h3>Why You Should Learn JavaScript</h3>
<p>If you are a web designer then knowledge of JavaScript will open up a myriad of new design possibilities for you. It&#8217;s going to be eye candy a go go! Not only that but you&#8217;ll be able to create some genuinely interesting form validation methods that would not be possible with just CSS and server-side script alone.</p>
<p>If you do not have a programming or development background then you will need to set aside some serious learning time as JavaScript will be quite a shock to your senses.</p>
<p>For all intents and purposes JavaScript is (almost) like using a fully functioning programming language, while HTML and CSS are anything but. As I was already familiar with PHP and ASP, diving into the big J wasn&#8217;t such a enormous step, but if this is your first introduction to functions, loops and variables then be prepared to suffer.</p>
<h3>Become an expert HTML and CSS Coder First</h3>
<p>Lets get this clear, it is unthinkable to tackle JavaScript without a sound knowledge of HTML and CSS. The three now go together like a brotherly triad.</p>
<p>You will need an awareness of HTML to use the DOM (more of which below) and most major JavaScript libraries now use CSS as a method of applying the script on the web page. For instance, Dojo and jQuery have incorporated the <a href="http://sizzlejs.com/">Sizzle Selector Engine</a> to harness the power of basic and advanced CSS for their libraries.</p>
<p>If you know how to push CSS to its limits then you&#8217;ll be equipped to do the same to jQuery.</p>
<h3>Use a JavaScript Library</h3>
<p>Occasionally I read an opinion on the web that jQuery isn&#8217;t proper JavaScript, and so consequently the developer isn&#8217;t  a proper JavaScript user. This argument is complete rubbish.</p>
<p>jQuery, and all the others, are 100% JavaScript. They primarily exist not to solve problems in the scripting language itself but to rectify inconsistencies between browsers.</p>
<p>If you consider CSS issues between the legacy Internet Explorer versions and the rest of the pack to be a headache then, oh boy, you just wait for JavaScript to send you crazy.</p>
<p>As an example below is the code that <a href="http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/">Andy Langton</a> uses to find the viewport width and height. Note the three different methods that are necessary for multi-browser support.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">   <span style="color: #003366; font-weight: bold;">var</span> viewportWidth<span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">var</span> viewportHeight<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">/* the more standards compliant browsers (mozilla/netscape/opera/IE8) use window.innerWidth and window.innerHeight*/</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">typeof</span> window.<span style="color: #660066;">innerWidth</span> <span style="color: #339933;">!=</span> <span style="color: #3366CC;">'undefined'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
        viewportWidth <span style="color: #339933;">=</span> window.<span style="color: #660066;">innerWidth</span><span style="color: #339933;">;</span>
        viewportHeight <span style="color: #339933;">=</span> window.<span style="color: #660066;">innerHeight</span><span style="color: #339933;">;</span>
        <span style="color: #009966; font-style: italic;">/* IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document) */</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">typeof</span> document.<span style="color: #660066;">documentElement</span> <span style="color: #339933;">!=</span> <span style="color: #3366CC;">'undefined'</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000066; font-weight: bold;">typeof</span> document.<span style="color: #660066;">documentElement</span>.<span style="color: #660066;">clientWidth</span> <span style="color: #339933;">!=</span> <span style="color: #3366CC;">'undefined'</span> <span style="color: #339933;">&amp;&amp;</span> document.<span style="color: #660066;">documentElement</span>.<span style="color: #660066;">clientWidth</span> <span style="color: #339933;">!==</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
        viewportWidth <span style="color: #339933;">=</span> document.<span style="color: #660066;">documentElement</span>.<span style="color: #660066;">clientWidth</span><span style="color: #339933;">;</span>
        viewportHeight <span style="color: #339933;">=</span> document.<span style="color: #660066;">documentElement</span>.<span style="color: #660066;">clientHeight</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
        viewportWidth <span style="color: #339933;">=</span> document.<span style="color: #660066;">getElementsByTagName</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'body'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">clientWidth</span><span style="color: #339933;">;</span>
        viewportHeight <span style="color: #339933;">=</span> document.<span style="color: #660066;">getElementsByTagName</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'body'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">clientHeight</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Alright, so after the slow death of IE6 the above code will be redundant, but there are a multitude of similar examples that could be given because the differences between Internet Explorer and the rest can be quite maddeningly bonkers.</p>
<p>JavaScript libraries will provide to you an easy way of dealing with issues that affect versions of older versions of Microsoft&#8217;s browser.</p>
<p>Freely using them is about understanding how Open Source works. The principles behind this programming philosophy is about finding a solution to a problem, and then allowing others to replicate the solution for their own purposes. This is why the Open Source approach is so effective. It doesn&#8217;t make you a lesser developer by relying on an Open Source library.</p>
<p>I started my educational quest at the beginning of 2010 with a copy of David Flanagan&#8217;s &#8216;JavaScript: the Definitive Guide&#8217; and enrolment on a UK Open University course. After a few months of trying learn raw JavaScript it become apparent to me that I needed the help of a library.</p>
<p>However, those first few formative months were extremely important as it gave me an appreciation of the DOM (Document Object Method) and problems associated therewith.</p>
<p>The DOM is, if you don&#8217;t know, how JavaScript interacts with the HTML page.</p>
<h3>Follow the DOM, not the Sizzle</h3>
<p>After several months of regularly using jQuery and Dojo I&#8217;ll now be returning to core JavaScript in 2011 and incorporating that into my code wherever possible.</p>
<p>Essentially, jQuery is a series of functions. It is important to understand that it is not there to replace JavaScript, but it is an aid to using it more quickly and effectively. Understand and use raw JavaScript first, and rely on jQuery or one of the other existing projects next if you must.</p>
<p>In jQuery this is how you would find a div with an id</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> exampleId <span style="color: #339933;">=</span> jQuery<span style="color: #009900;">&#40;</span>#example<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>While in DOM JavaScript it is:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> exampleId <span style="color: #339933;">=</span> document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span>example<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Use the DOM object method wherever possible and don&#8217;t pass it through a function unless it is necessary to do so.</p>
<p>There is some criticism that JavaScript libraries carry too much code bloat, but by using the DOM and the JS core you minimise this issue.</p>
<p>In a similar spirit, I also use the core JavaScript loops and arrays rather than anything provided by jQuery. The point is to use a library, but don&#8217;t be dependent on it. For that you&#8217;ll need to understand the differences and then make decisions about when is the appropriate moment to use a somebody else&#8217;s script, and when you shouldn&#8217;t.</p>
<p>There is though one good reason why you should go through all the pain of forsaking jQuery and tackling JavaScript without an aid and that is because it will make you immensely employable.</p>
<p>You quite likely to be head hunted by an agency if you have advanced JavaScript experience as it is a skillset that is currently much in demand, and it would be fair to forecast the future and state that JavaScript will become an increasingly dominant web technology in coming years, rather than a shrinking one.</p>
<h3>Try to Use Object Detection, not Browser Sniffing</h3>
<p>Even with the best equipped JavaScript library, you will still regularly run into issues with IE that needs special attention.</p>
<p>If the JavaScript is used for non-essential eye candy, it may well be the best option to forget about IE 6 or 7 by creating a conditional statement that blocks both or either of these browsers from using the code. After all, time is money ñ and you have your sanity to worry about.</p>
<p>It is possible to detect the make and version number of a browser but the code to do so can be unreliable; indeed, jQuery have recommended against its use. A more trustworthy alternative is to use object detection.</p>
<p>jQuery has a limited set of object detection based around <a href="http://api.jquery.com/jQuery.support">support</a>, but <a href="http://www.modernizr.com/">Modernizr</a> is a well-loved and well-respected script.</p>
<p>An example of  Modernizr in action. The code below tests of HTML local.storage.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>Modernizr.<span style="color: #660066;">localstorage</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// For browers Chrome 4+; Firefox 3.5+; IE8+; Opera 10.5+; Safari 4+; plus iPhone 2.0+; and Android 2.0+.</span>
&nbsp;
<span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Use cookies for all the others</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>This is the code I use to run JS in any browser apart from Internet Explorer 6:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>document.<span style="color: #660066;">documentElement</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000066; font-weight: bold;">typeof</span> document.<span style="color: #660066;">documentElement</span>.<span style="color: #660066;">style</span>.<span style="color: #660066;">maxHeight</span> <span style="color: #339933;">!=</span> <span style="color: #3366CC;">&quot;undefined&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// code here</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>JavaScript purists might have little fit at the above slice of code as they consider objects should only be used for the object it is testing for, but you are never going to have perfection when comes to  Internet Explorer.</p>
<h3>Use JSLint</h3>
<p><a href="http://www.jslint.com/">JSLint</a> is kind of like a JavaScript validator, or a a code quality tool as it is described on their website. If you are new to this script and are wondering why your code isn&#8217;t working then cut and paste it into JSLint and let the automatically generated suggestions help you debug your work.</p>
<p>Even a single wrongly placed comma can stop the whole script from running, especially in IE which is a lot less tolerant of mistakes.</p>
<h3>Keep your Code Tidy and Use Comments</h3>
<p>If you write JavaScript without explaining your code you are either a complete arsehole (because you couldn&#8217;t care less about the developer after you) or you are a masochist, because when you return to your code a few months later it will be difficult to understand.</p>
<p>Use comments liberally. It is better to have too many comments then too few, at least then you can delete unnecessary comments at the end of the job (refactoring comments?!).</p>
<p>In JavaScript there are two different ways to leave comments. They are:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// This is a single line comment</span>
&nbsp;
<span style="color: #006600; font-style: italic;">/*
This is a block of comments
*/</span></pre></td></tr></table></div>

<p>Likewise keep your code need and tidy and you can do that by using the rather wonderful <a href="http://jsbeautifier.org/">JSBeautifier</a>. This will indent your code into an easy to read pattern.</p>
<p>Also, I have now started to add a dollar sign to my variables akin to PHP. Unlike in PHP, there is no such requirement in JavaScript but nevertheless I find it easier on the eye when quickly scanning a document.</p>
<h3>Conclusion</h3>
<p>JavaScript with the DOM bumps mentioned above can be both infuriating and frustrating. But, like anything else, persistence pays off ñ and you may even grow to quite like the cantankerous old bugger.</p>
<p>One thing for sure though is that JavaScript is a key web technology of the present and the future. You ignore it at your peril. So buy some books, watch some Think Vitamin tutorials and get coding!</p>
<p>If you have any recommendations for JavaScript newbies that builds on this article, whether books, guides or techniques &#8211; then please post them below.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/tips-on-learning-javascript/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>37signals &#8216;Cinco&#8217; framework to be open-sourced</title>
		<link>http://thinkvitamin.com/code/javascript/37signals-cinco-framework-to-be-open-sourced/</link>
		<comments>http://thinkvitamin.com/code/javascript/37signals-cinco-framework-to-be-open-sourced/#comments</comments>
		<pubDate>Wed, 02 Feb 2011 05:29:17 +0000</pubDate>
		<dc:creator>Ryan Carson</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Articles]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=11869</guid>
		<description><![CDATA[Revealed in a comment by DHH on this blog post, 37signals is definitely going to open-source their new framework for single-page JavaScript apps. Very excited to see how this develops. Here&#8217;s DHH&#8217;s comment &#8230; Hold on for our new Cinco framework. It&#8217;s basically Rails for single-page JS apps. We just used it to introduce Basecamp [...]]]></description>
			<content:encoded><![CDATA[<p>Revealed in a <a href="http://harry.me/2011/01/27/today-web-development-sucks/#comment-138188999">comment by DHH on this blog post</a>, 37signals is definitely going to open-source their new framework for single-page JavaScript apps. Very excited to see how this develops. Here&#8217;s DHH&#8217;s comment &#8230;<span id="more-11869"></span></p>
<blockquote><p>Hold on for our new Cinco framework. It&#8217;s basically Rails for single-page JS apps. We just used it to <a href="http://37signals.com/svn/posts/2761-launch-basecamp-mobile">introduce Basecamp Mobile</a>. A bunch of the supporting frameworks have already been released. The template language eco and the compiler stitch. We&#8217;ll be releasing the rest of the pieces in due time.</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/javascript/37signals-cinco-framework-to-be-open-sourced/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Create JavaScript Apps with Backbone.js</title>
		<link>http://thinkvitamin.com/code/create-javascript-apps-with-backbone-js/</link>
		<comments>http://thinkvitamin.com/code/create-javascript-apps-with-backbone-js/#comments</comments>
		<pubDate>Wed, 12 Jan 2011 20:44:15 +0000</pubDate>
		<dc:creator>Jim Hoskins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=11461</guid>
		<description><![CDATA[Building JavaScript applications for the browser can become really complicated. Until recently we had two main options: create your application structure from scratch, or use a JavaScript application framework like Cappucinno or SproutCore. Building a large JavaScript application without a framework can lead to unorganized, difficult to maintain code. Libraries like jQuery and Prototype offer [...]]]></description>
			<content:encoded><![CDATA[<p>Building JavaScript applications for the browser can become really complicated. Until recently we had two main options: create your application structure from scratch, or use a JavaScript application framework like <a title="Cappuccino" href="http://cappuccino.org/">Cappucinno</a> or <a title="SproutCore" href="http://www.sproutcore.com/">SproutCore</a>.</p>
<p>Building a large JavaScript application without a framework can lead to unorganized, difficult to maintain code. Libraries like <a title="jQuery" href="http://jquery.com">jQuery</a> and <a title="Prototype" href="http://www.prototypejs.org/">Prototype</a> offer us great tools to normalize DOM APIs and browser quirks, but don&#8217;t offer much direction as to how to organize our application logic and data.</p>
<p>On the other side of the spectrum, Frameworks like SproutCore and Cappucinno offer extremely robust application tools like controllers, models, key value observing and more. However these frameworks also include a large UI library, and a very steep learning curve.<span id="more-11461"></span></p>
<p>So what is there in the middle, for us writing medium to large size JavaScript applications? <a title="Yehuda Katz speaking about the SproutCore: Amber project" href="http://blog.sproutcore.com/post/1711425620/first-san-francisco-meetup-in-a-long-time-yehuda">The SproutCore: Amber </a>project promises to extract some of the most useful components of SproutCore to create a &#8220;light&#8221; version that can be used anywhere.</p>
<p>37Signals has taken the route of creating <a title="New Rails-like Framework from 37signals for HTML5 Mobile Apps" href="http://thinkvitamin.com/mobile/new-rails-like-framework-from-37signals-for-html5-mobile-apps/">their own framework</a>, and there is a possibility it may be released as an open source project, much like<a href="http://rubyonrails.org"> Ruby on Rails</a>. My favorite framework that I have had the chance to use recently is <a title="Backbone.js" href="http://documentcloud.github.com/backbone/">Backbone.js</a>.</p>
<p><img title="backbone" src="http://thinkvitamin.com/wp-content/uploads/2011/01/backbone.png" alt="Backbone.js" /></p>
<p><a title="Backbone.js" href="http://documentcloud.github.com/backbone/">Backbone.js</a> is a very lightweight toolkit that provides things like models, controllers, and views. The models allow you to keep track of the data in your application, as well as organize your app&#8217;s business logic.</p>
<p>The models can also very easily interact with a RESTful API provided by your web application, making much easier to synchronize data between your frontend and backend applications.</p>
<p>The views offer the ability to easily update your page elements when the data in the model is updated. The controllers offer utilities for managing changes in your application state by utilizing the fragment, the part of the URL after the #.</p>
<p>Backbone.js provides the tools, but does not impose too much structure on your application. I have found this to be a very good balance. I am able to integrate it fairly easily into my existing applications, with great benefits.</p>
<p>The downside the this is that it does take a little bit of reading and experimenting to see exactly all of the pieces of Backbone.js fit together. I suggest taking a look at not only the documentation, but also the <a href="http://documentcloud.github.com/backbone/examples/todos/index.html">Todo List</a> application, and its <a title="Todo List annotated source" href="http://documentcloud.github.com/backbone/docs/todos.html">annotated source</a>.</p>
<p>Backbone.js is intentionally very small (3.9kb packed and gzipped) and it&#8217;s only hard dependency is underscore.js, which provides a library of useful general purpose JavaScript functions. Backbone.js can also use <a title="jQuery" href="http://jquery.com/">jQuery</a> or <a title="zepto.js" href="http://zeptojs.com/">zepto.js</a> for helping with view functionality.</p>
<p>What are your favorite tools for organizing JavaScript applications?</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/create-javascript-apps-with-backbone-js/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>How to Build a Simple Web Service with Node.js</title>
		<link>http://thinkvitamin.com/code/javascript/how-to-build-a-simple-web-service-with-node-js/</link>
		<comments>http://thinkvitamin.com/code/javascript/how-to-build-a-simple-web-service-with-node-js/#comments</comments>
		<pubDate>Wed, 12 Jan 2011 09:01:31 +0000</pubDate>
		<dc:creator>Ryan Carson</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Videos]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=10604</guid>
		<description><![CDATA[This 9-minute video tutorial on JavaScript Node.js, we expand upon the simple HTTP server example, and create a web service that parses the URL to perform simple functions. This video is from Think Vitamin Membership, a high-quality video training site, curated by us at Carsonified and Think Vitamin, with hundreds of short videos on topics like &#8230; Accessibility [...]]]></description>
			<content:encoded><![CDATA[<p>This 9-minute video tutorial on <a href="http://membership.thinkvitamin.com/library/javascript/nodejs/building-a-simple-web-service?cid=106">JavaScript Node.js</a>, we expand upon the simple HTTP server example, and create a web service that parses the URL to perform simple functions.</p>
<p><a href="http://membership.thinkvitamin.com/library/javascript/nodejs/building-a-simple-web-service?cid=106"><img src="http://img.skitch.com/20101209-cq5q1wbpmb3jdftw93i8y4bgj8.jpg" alt="Screengrab of video teaching about PHP variables and functions" /></a></p>
<p>This video is from <a href="http://membership.thinkvitamin.com/?cid=106">Think Vitamin Membership</a>, a high-quality video training site, curated by us at Carsonified and Think Vitamin, with hundreds of short videos on topics like &#8230;</p>
<ul>
<li><a href="http://membership.thinkvitamin.com/library/accessibility/?cid=106">Accessibility</a></li>
<li><a href="http://membership.thinkvitamin.com/library/css3/?cid=106">CSS3</a></li>
<li><a href="http://membership.thinkvitamin.com/library/design/?cid=106">Design</a></li>
<li<a href="http://membership.thinkvitamin.com/library/django/?cid=106">Django</a></li>
<li><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106">HTML &amp; CSS</a></li>
<li><a href="http://membership.thinkvitamin.com/library/html5/?cid=106">HTML5</a></li>
<li><a href="http://membership.thinkvitamin.com/library/javascript/?cid=106">JavaScript</a></li>
<li><a href="http://membership.thinkvitamin.com/library/jquery/?cid=106">jQuery</a></li>
<li><a href="http://membership.thinkvitamin.com/library/nosql/?cid=106">NoSQL</a></li>
<li><a href="http://membership.thinkvitamin.com/library/php/?cid=106">PHP</a></li>
<li><a href="https://membership.thinkvitamin.com/library/responsive-web-design/?cid=106">Responsive Web Design</a></li>
<li><a href="http://membership.thinkvitamin.com/library/ruby/?cid=106">Ruby</a></li>
<li><a href="http://membership.thinkvitamin.com/library/ruby-on-rails/?cid=106">Ruby on Rails</a></li>
<li><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106">SASS</a></li>
<li><a href="http://membership.thinkvitamin.com/library/ux/?cid=106">UX</a></li>
<li><a href="http://membership.thinkvitamin.com/library/version-control?cid=106">Version Control</a></li>
<li><a href="http://membership.thinkvitamin.com/library/wordpress?cid=106">WordPress Theme Design</a></li>
</ul>
<p>10 new videos are added every week, so it&#8217;s a great way to stay up-to-date on all the latest technology and methods. Browse the entire <a href="http://membership.thinkvitamin.com/library/?cid=106">library of videos</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/javascript/how-to-build-a-simple-web-service-with-node-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript DOM event tutorial</title>
		<link>http://thinkvitamin.com/code/javascript-dom-event-basics/</link>
		<comments>http://thinkvitamin.com/code/javascript-dom-event-basics/#comments</comments>
		<pubDate>Thu, 25 Nov 2010 14:53:25 +0000</pubDate>
		<dc:creator>Ryan Carson</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=9380</guid>
		<description><![CDATA[In this 8-minute JavaScript DOM tutorial video we look at how to bind event listeners to your DOM elements. This video is from Think Vitamin Membership, a high-quality video training site, curated by us at Carsonified and Think Vitamin, with hundreds of short videos on topics like &#8230; Accessibility CSS3 Design Django HTML &#38; CSS HTML5 JavaScript [...]]]></description>
			<content:encoded><![CDATA[<p>In this 8-minute <a href="http://membership.thinkvitamin.com/library/javascript/dom-programming/event-basics?cid=106">JavaScript DOM tutorial video</a> we look at how to bind event listeners to your DOM elements.</p>
<p><a href="http://membership.thinkvitamin.com/library/javascript/dom-programming/event-basics?cid=106"><img src="http://img.skitch.com/20101124-tcu75xsidfrah4x5ebmm34h5fs.png" alt="Screengrab of video" /></a></p>
<p>This video is from <a href="http://membership.thinkvitamin.com/?cid=106">Think Vitamin Membership</a>, a high-quality video training site, curated by us at Carsonified and Think Vitamin, with hundreds of short videos on topics like &#8230;</p>
<ul>
<li><a href="http://membership.thinkvitamin.com/library/accessibility/?cid=106">Accessibility</a></li>
<li><a href="http://membership.thinkvitamin.com/library/accessibility/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/css3/?cid=106">CSS3</a></li>
<li><a href="http://membership.thinkvitamin.com/library/css3/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/design/?cid=106">Design</a></li>
<li><a href="http://membership.thinkvitamin.com/library/design/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/django/?cid=106">Django</a></li>
<li><a href="http://membership.thinkvitamin.com/library/django/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106">HTML &amp; CSS</a></li>
<li><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/html5/?cid=106">HTML5</a></li>
<li><a href="http://membership.thinkvitamin.com/library/html5/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/javascript/?cid=106">JavaScript</a></li>
<li><a href="http://membership.thinkvitamin.com/library/javascript/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/jquery/?cid=106">jQuery</a></li>
<li><a href="http://membership.thinkvitamin.com/library/jquery/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/nosql/?cid=106">NoSQL</a></li>
<li><a href="http://membership.thinkvitamin.com/library/nosql/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/php/?cid=106">PHP</a></li>
<li><a href="http://membership.thinkvitamin.com/library/php/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/ruby/?cid=106">Ruby</a></li>
<li><a href="http://membership.thinkvitamin.com/library/ruby/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/ruby-on-rails/?cid=106">Ruby on Rails</a></li>
<li><a href="http://membership.thinkvitamin.com/library/ruby-on-rails/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106">SASS</a></li>
<li><a href="http://membership.thinkvitamin.com/library/html-css/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/ux/?cid=106">UX</a></li>
<li><a href="http://membership.thinkvitamin.com/library/ux/?cid=106"></a><a href="http://membership.thinkvitamin.com/library/version-control?cid=106">Version Control</a></li>
</ul>
<p>10 new videos are added every week, so it&#8217;s a great way to stay up-to-date on all the latest technology and methods. Browse the entire <a href="http://membership.thinkvitamin.com/library/?cid=106">library of videos</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/javascript-dom-event-basics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Free JavaScript &amp; JQuery E-Book</title>
		<link>http://thinkvitamin.com/code/free-javascript-jquery-e-book/</link>
		<comments>http://thinkvitamin.com/code/free-javascript-jquery-e-book/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 10:48:01 +0000</pubDate>
		<dc:creator>Keir Whitaker</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Links]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=9897</guid>
		<description><![CDATA[&#8220;Essential JavaScript &#038; jQuery Design Patterns For Beginners&#8221; by Addy Osmani looks interesting. As Addy says &#8220;design patterns are reusable solutions to commonly occurring problems in software development and are a very useful tool to have at your disposal.&#8221;]]></description>
			<content:encoded><![CDATA[<p>&#8220;<a href="http://addyosmani.com/blog/essentialjsdesignpatterns/">Essential JavaScript &#038; jQuery Design Patterns For Beginners</a>&#8221; by <a href="http://addyosmani.com/">Addy Osmani</a> looks interesting. As Addy says &#8220;design patterns are reusable solutions to commonly occurring problems in software development and are a very useful tool to have at your disposal.&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/free-javascript-jquery-e-book/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>New Mobile Web Framework</title>
		<link>http://thinkvitamin.com/code/new-mobile-web-framework/</link>
		<comments>http://thinkvitamin.com/code/new-mobile-web-framework/#comments</comments>
		<pubDate>Tue, 09 Nov 2010 09:29:59 +0000</pubDate>
		<dc:creator>Keir Whitaker</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Links]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=9682</guid>
		<description><![CDATA[Zepto.js is a new JavaScript framework for mobile apps and sites from Thomas Fuchs. It&#8217;s super small coming in at under 2k and features a jQuery-compatible syntax. You can learn more over on by having a quick look at a presentation from the recent vienna.js meetup.]]></description>
			<content:encoded><![CDATA[<p><a href="http://zeptojs.com/">Zepto.js</a> is a new JavaScript framework for mobile apps and sites from <a href="http://mir.aculo.us/">Thomas Fuchs</a>. It&#8217;s super small coming in at under 2k and features a jQuery-compatible syntax. You can learn more over on by having a quick look at a <a href="http://mir.aculo.us/2010/10/28/zepto-js-a-jquery-compatible-mobile-javascript-framework-in-2k-presentation/">presentation</a> from the recent <a href="http://viennajs.org/">vienna.js</a> meetup.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/new-mobile-web-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Around the Web: Disrupt Disbands, Grouspawn, Twitter’s Javascript API</title>
		<link>http://thinkvitamin.com/business/around-the-web-disrupt-disbands-grouspawn-twitters-javascript-api/</link>
		<comments>http://thinkvitamin.com/business/around-the-web-disrupt-disbands-grouspawn-twitters-javascript-api/#comments</comments>
		<pubDate>Thu, 30 Sep 2010 04:54:20 +0000</pubDate>
		<dc:creator>Chrissie Brodigan</dc:creator>
				<category><![CDATA[Business]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=7960</guid>
		<description><![CDATA[It&#8217;s Wednesday, so this mid-week roundup is devoted to all things business and development, and a little focused on news around TechCrunch Disrupt. Some links are newsworthy, some retweeted across Twitter, and others just meet our “awesomeness” requirement, and regardless we hope you’ll enjoy them. Without further delay: From TechCrunch Disrupt, on the Angel v. [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s Wednesday, so this mid-week roundup is devoted to all things business and development, and a little focused on news around TechCrunch Disrupt. Some links are newsworthy, some retweeted across Twitter, and others just meet our “awesomeness” requirement, and regardless we hope you’ll enjoy them. Without further delay:<span id="more-7960"></span></p>
<ul>
<li>From TechCrunch Disrupt, on the Angel v. VC panel, Mark Suster cogently recaps and writes, <a href="http://www.bothsidesofthetable.com/2010/09/27/what-i-would-have-said-at-techcrunch-disrupt/" target="_blank">&#8220;What I *Would Have* Said at TechCrunch Disrupt.</a></li>
<li>This one is for javascript API lovers <a href="http://engineering.twitter.com/2010/09/tech-behind-new-twittercom.html" target="_blank">The Tech Behind New Twitter</a> (via Twitter&#8217;s Engineering blog, which I only just found by attending TC Disrupt!)</li>
<li>Brilliant business or just bizarre? Groupon Launched <a href="http://grouspawn.com" target="_blank">&#8220;Grouspawn&#8221;</a> a dating service for users who meet on Groupon Dates &amp; have a baby later (<a href="http://techcrunch.com/2010/09/29/groupon-babies/" target="_blank">announced by ceo Andrew Mason at TC Disrupt</a>) hint: for a javascript Easter egg &#8211; scroll to the bottom and hover over the image in the lower left.</li>
<li>Malcolm Gladwell writes, <a href="http://www.newyorker.com/reporting/2010/10/04/101004fa_fact_gladwell?currentPage=all" target="_blank">Why the Revolution Will Not Be Tweeted</a></li>
<li>Mailchimp on going Freemium <a href="http://www.mailchimp.com/blog/going-freemium-one-year-later/" target="_blank">&#8220;One Year later&#8221;</a></li>
</ul>
<p>Wildcard: Thank goodness for <a href="http://twitter.com/oatmeal" target="_blank">@oatmeal,</a> <a href="http://theoatmeal.com/comics/design_changes" target="_blank">&#8220;Why You Don&#8217;t Like Changes to Your Design&#8221;</a></p>
<p>Please shoot me links to projects your working on or awesome things you&#8217;ve released! <a href="mailto:news@thinkvitamin.com">news@thinkvitamin.com</a></p>
<p>Handpicked by Chrissie (<a href="http://twitter.com/tenaciouscb" target="_blank">@tenaciouscb</a>)</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/business/around-the-web-disrupt-disbands-grouspawn-twitters-javascript-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Twitter @Anywhere Revisited</title>
		<link>http://thinkvitamin.com/code/twitter-anywhere-revisited/</link>
		<comments>http://thinkvitamin.com/code/twitter-anywhere-revisited/#comments</comments>
		<pubDate>Mon, 06 Sep 2010 14:00:01 +0000</pubDate>
		<dc:creator>Richard Shepherd</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=7200</guid>
		<description><![CDATA[I must be honest, I was pretty unimpressed with Twitter @Anywhere when it first launched earlier this year. Of course I hadn’t bothered to check it out, but it seemed like ‘Integration Lite’ &#8211; just a very simple way for bloggers to include Twitter on their site. As Wired reported back in March Twitter’s Evan [...]]]></description>
			<content:encoded><![CDATA[<p>I must be honest, I was pretty unimpressed with <a href="http://dev.twitter.com/anywhere" target="_blank">Twitter @Anywhere</a> when it first launched earlier this year. Of course I hadn’t bothered to check it out, but it seemed like ‘Integration Lite’ &#8211; just a very simple way for bloggers to include Twitter on their site.</p>
<p>As <a href="http://www.wired.com/epicenter/2010/03/sxsw-twitter-ceo-evan-williams-launches-anywhere/" target="_blank">Wired reported back in March</a> Twitter’s Evan Williams promised <tt>@Anywhere</tt> would “reduce friction.”</p>
<blockquote><p>“You could be reading your favourite columnist [and] you can easily tweet from the column itself if […] you may just want to follow the columnist […] without going back to Twitter.”</p></blockquote>
<p>Amongst the launch partners for <tt>@Anywhere</tt> were <a href="http://digg.com/" target="_blank">Digg</a>, <a href="http://www.huffingtonpost.com/" target="_blank">Huffington Post</a> and <a href="http://www.nytimes.com/" target="_blank">The New York Times</a>. And one of the most high profile users the little known <a href="http://followfinder.googlelabs.com/" target="_blank">Follow Finder</a> from The Mighty Google.</p>
<p style="text-align: center;"><a href="http://www.followfinder.googlelabs.com/"><img class="size-medium wp-image-7201  aligncenter" src="http://thinkvitamin.com/wp-content/uploads/2010/09/followfinder.png" alt="" width="470" /></a></p>
<p>But alas, it was more a fizzle than a firework and like many at the time I was rather nonplussed.</p>
<p>I’m pleased to say I’ve been completely converted. Not only is playing with Twitter inherently a cool thing to do, it can add real power to your website and more importantly your web applications. Indeed, it’s the scope for easily including Twitter functionality in web applications that’s really exciting.</p>
<p>So let’s take a look at some of this functionality and how you can use it. You’ll be up and running in just minutes, and after briefly looking at some of the simpler methods we’ll dive straight in to integrating Twitter right into your web app.<span id="more-7200"></span></p>
<h3>Registering for @Anywhere</h3>
<p>The first thing you need to do is register for an Application ID. It’s ridiculously simply to get, but perhaps worth some explaining to the uninitiated. First head on over to <a href="http://dev.twitter.com/anywhere" target="_blank">http://dev.twitter.com/anywhere</a> and click on the &#8216;Start using it now&#8217; button.</p>
<p style="text-align: center;"><a href="http://dev.twitter.com/anywhere"><img class="size-medium wp-image-7205  aligncenter" src="http://thinkvitamin.com/wp-content/uploads/2010/09/anywherehomepage.png" alt="" width="470" /></a></p>
<p>You’ll be swiftly taken to a one-page form where you register your app. The first question, particularly to those new at this whole API game, is ‘what if I don’t have an app?’.</p>
<p>Let’s say you just want to use hovercards on your blog. Or let’s say you want your users to be able to tweet about your blog articles by providing them a tweet box at the footer of each page. Not really an ‘app’ is it? More of a feature, a widget perhaps.</p>
<p>Well, in the big wide world of APIs what you have is a web app my friend and you need to accept it! Even the humble ‘Linkify’ method (automatically turning all Twitter usernames into links to their profiles) makes your humble blog post a web application of sorts. Deal with this fuzzy distinction and move on. We need that app ID!!</p>
<p><em><strong>NB:</strong> For the rest of this article I’ll use the term app/application, but it equally applies to your site/blog</em></p>
<h3>Completing the Form</h3>
<p><strong>Application Name</strong></p>
<p>Name your application wisely because users will see this name when they are asked to authorise your app; although it’s worth noting that certain functionality, like linkifying and hovercards, doesn’t require users to see this name.</p>
<p><strong>Callback URL</strong></p>
<p>If you intend to use some of the <tt>@Anywhere</tt> functionality which requires users to authenticate your app then Twitter needs to know which page to send the API response to (which includes lots of handy data about the user that we can tap into using JavaScript!). The callback URL is most likely the very same page that has called the authentication.</p>
<p style="text-align: center;"><a href="http://dev.twitter.com/anywhere/apps/new"><img class="size-medium wp-image-7210  aligncenter" src="http://thinkvitamin.com/wp-content/uploads/2010/09/register.png" alt="" width="470"  /></a></p>
<p>If you’re only using simple <tt>@Anywhere</tt> methods like linkify you can just put your site’s homepage in here.</p>
<p><strong>Default Access Type</strong></p>
<p>This defaults to Read-only, but we want to use some advanced <tt>@Anywhere</tt> methods so make sure you change this to Read &amp; Write.</p>
<h3>Basic functions</h3>
<p>Okay, we’ve filled up this car with petrol/gas so it’s time to take it out for a spin! Open a new HTML document and in the <tt>&lt;head&gt;</tt> of the document include the following line of code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;http://platform.twitter.com/anywhere.js?id=YOUR-APP-ID-GOES-HERE&amp;v=1&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>Don&#8217;t forget to add your app ID into the URL.</p>
<p>Before I go on I feel I must address those of you who now resemble Yosamite Sam, with steam coming out of their ears at the idea of ever including a JavaScript file at the top of a page. But including the <tt>anywhere.js</tt> file in the head makes a lot of sense for a number of reasons, outlined by Twitter themselves:</p>
<ul>
<li>It’s small. Less than 3kb to be exact, gzipped up into a tiny package.</li>
<li>All dependencies for <tt>@Anywhere</tt> features are loaded asynchronously, so you only get what you need when you need it.</li>
<li>Most importantly, when a user logs in and authenticates your app the Twitter login page redirects back to the callback URL. This happens in a pop-up window, so if anywhere.js is at the bottom of the page it’ll mean that the user sees your site in that pop-up before it disappears. Which looks bad and, as Twitter put it, ‘is a poor user experience’.</li>
</ul>
<p>So leave it in the <tt>&lt;head&gt;</tt> and let’s move on. Now we need to initialise the a global <tt>@Anywhere</tt> object which we do with:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>For those who have tried to run that script, you’ll see that nothing happens. That’s because we need to give it a callback function of some sort. For example, to linkify every Twitter username on a page you simply need:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
T.<span style="color: #660066;">linkifyUsers</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>What’s with the capital ‘T’? Well that’s just Twitter’s convention so we’ll stick with it, but you’re welcome to change it to a more descriptive name. An instance of the API client is passed into T for us to then call methods on, just as we’ve done above.</p>
<p>Run that puppy on a page which has a username in the markup and watch it magically turn into a link. It was roughly about now that I gave up on <tt>@Anywhere</tt> earlier this year, but stick with me here &#8211; it get’s better.</p>
<h3>Hovercards</h3>
<p>Another method that works in a similar way is Hovercards, which work in the same way.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
T.<span style="color: #660066;">hovercards</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p><img class="aligncenter size-full wp-image-7225" src="http://thinkvitamin.com/wp-content/uploads/2010/08/hovercard2.png" alt="" width="313" height="271" /></p>
<p>With linkifying and hovercarding under our belts its worth looking at another couple of handy features.</p>
<h3>Scope</h3>
<p>You can limit the scope of a method by passing in a CSS selector. A lot of you will spot that this looks a lot like jQuery and that’s because it’s using the same <a href="http://sizzlejs.com/" target="_blank">Sizzle</a> selection engine.</p>
<p>For example, to linkify usernames only in the DIV with an ID of ‘sidebar’ you could use the following code</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
T<span style="color: #009900;">&#40;</span>‘#sidebar’<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">linkifyUsers</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<h3>Configuration Options</h3>
<p>There are a number of option that we can pass to these methods, which we do in an object literal. Again, if you&#8217;ve used jQuery before then this will be nothing new to you:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
T<span style="color: #009900;">&#40;</span>‘#sidebar’<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">hovercards</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span> expanded<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>Adding <tt>{expanded: true}</tt> does exactly what it says &#8211; it renders the Hovercard in it&#8217;s expanded form from the off, rather than waiting for the user to click &#8216;more&#8217;.</p>
<h3>Moving Swiftly On</h3>
<p>I’m going to skip a bit here, which relates to some of the other configuration options you can use with the various &#8220;Anywhere methods. I highly recommend Twitter’s own documentation which you can find at <a href="http://dev.twitter.com/anywhere/begin" target="_blank">http://dev.twitter.com/anywhere/begin</a>.</p>
<h3>Getting more Advanced</h3>
<p>If you’ve spent much time surfing the interweb you’ve at some point seen that pop-up window asking you if you authorise an app or a site to play with your Twitter account. </p>
<p>If, like me, you blindly click yes you give that site direct access to lots of your personal (albeit public) information. Normally this isn’t a problem, but with great power comes great responsibility &#8211; as James Cunningham of <a href="http://twifficiency.com/" target="_blank">Twifficiency</a> fame (more at <a href="http://techcrunch.com/2010/08/17/twifficiency/" target="_blank">TechCrunch</a>).</p>
<p><img class="aligncenter size-medium wp-image-7211" src="http://thinkvitamin.com/wp-content/uploads/2010/09/authorise.png" alt="" width="470" height="" /></p>
<p>There are a couple of ways <tt>@Anywhere</tt> uses this connectivity. The first is with built in functions like the Tweet Box and the Follow button. Both need the user to login to Twitter and authorise your app, so both will cause the authorisation pop-up. We can call both like so:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
T<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#follow-button'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">followButton</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;richardshepherd&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
T<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#tweet-box'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">tweetBox</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>This places a follow button in the element with an ID of &#8216;follow-button&#8217; (and which is set to follow my Twitter account!), and a tweetbox in the element with an ID of &#8216;tweet-box&#8217;.</p>
<p><img class="aligncenter size-medium wp-image-7234" src="http://thinkvitamin.com/wp-content/uploads/2010/08/tweetbox-300x77.jpg" alt="" width="300" height="77" /></p>
<p>You’ll can find further details of the Tweet Box and Follow Buttons in the <a href="http://dev.twitter.com/anywhere/begin" target="_blank">official documentation</a>, but I think it get’s much more exciting to look at connecting your app with someone’s Twitter account and pulling information from their public profile. So let’s go ahead and crank things up! It’s surprisingly simple.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
T<span style="color: #009900;">&#40;</span>‘#connect’<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">connectButton</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span> size<span style="color: #339933;">:</span> “medium” <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>And that’s it. Try it out, and you’ll see the familiar pop-up asking for you to authorise your app (the name you gave it when you signed up). You can change the size be replacing ‘medium’ with ‘small’, ‘large’ or ‘xlarge’.</p>
<p style="text-align: center;"><img class="size-full wp-image-7214  aligncenter" src="http://thinkvitamin.com/wp-content/uploads/2010/08/connectwtwitter.png" alt="" width="256" height="50" /></p>
<p>Medium is the default, so if you’re happy with that you can remove it from the code. But how about your own custom connect button &#8211; how cool would that be? It turns out that the Twitter API has a <tt>signIn</tt> method which we can attach to any element: text, image or whatever you fancy.</p>
<p>Let’s say you have created your own CSS rollover button, applied to a span with and ID of twitterLogin. Here’s how you’d use JavaScript and the Twitter API to hook the signIn method to that span:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span>‘twitterLogin’<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">onclick</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>
T.<span style="color: #660066;">signIn</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>We are now freed from the shackles of Twitter’s own graphics and buttons, which makes it possible to create a unique experience for your own app or site. If the user is logged in, the pop-up window will simply ask them to authorise your app. If they aren’t logged in to Twitter it will also ask them for their login details.</p>
<h3>I Can Haz your Details?</h3>
<p>So your web app now has a connect button, and let’s assume your user has clicked it and logged in/authorised your app. Sweet. What next?</p>
<p>You should have set the Twitter callback URL to the same page as your web app, which means the pop-up will disappear and your page will be sent a bunch of new data (think of it as an AJAX request and response). This means you can use Javascript to check if the user is connected with the rather handy <tt>isConnected</tt> method. And, assuming it’s all gone to plan, the <tt>currentUser</tt> property contains lots of handy information.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script<span style="color: #339933;">&gt;</span>
twttr.<span style="color: #660066;">anywhere</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>T.<span style="color: #660066;">isConnected</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #006600; font-style: italic;">// This user is connected. Awesome!</span>
<span style="color: #003366; font-weight: bold;">var</span> user <span style="color: #339933;">=</span> T.<span style="color: #660066;">currentUser</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> screenName <span style="color: #339933;">=</span> user.<span style="color: #660066;">data</span><span style="color: #009900;">&#40;</span>‘screen_name’<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>‘Hi there ‘ <span style="color: #339933;">+</span> screenName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
<span style="color: #006600; font-style: italic;">// the user isn’t connected, so probably best to show them</span>
<span style="color: #006600; font-style: italic;">// a connect button!</span>
T<span style="color: #009900;">&#40;</span>‘#twitterLogin’<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">connectButton</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>Admittedly the use of a JavaScript alert here is almost criminal, but you get the idea. Include jQuery and you can start injecting the DOM with lots of Twitter goodness, personalising the user’s experience.</p>
<p>So what other properties can we access, apart from Screen Name? Well, pretty much all of the user’s public profile information is up for grabs. Here are some of the most useful:</p>
<ul>
<li>description</li>
<li> followers_count</li>
<li> following</li>
<li> profile_image_url</li>
<li> location</li>
<li> name</li>
<li> time_zone</li>
</ul>
<p>And you can check out a full like at <a href="http://dev.twitter.com/anywhere/begin#user-properties" target="_blank">http://dev.twitter.com/anywhere/begin#user-properties</a></p>
<p>So using our example above you could access the profile image with:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> imageHTML <span style="color: #339933;">=</span> ‘<span style="color: #339933;">&lt;</span>img src<span style="color: #339933;">=</span>”’ <span style="color: #339933;">+</span> user.<span style="color: #660066;">data</span><span style="color: #009900;">&#40;</span>‘profile_image_url’<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> ‘“ <span style="color: #339933;">/&gt;</span>’<span style="color: #339933;">;</span></pre></td></tr></table></div>

<h3>What Next?</h3>
<p>Of course <tt>@Anywhere</tt> is no substitute for server side integration with the Twitter API, but it’s a lean way of enhancing your web app/web sites experience for Twitter users.</p>
<p>Have you started to use <tt>@Anywhere</tt>? If so, tell us how and whether you think it’s enhanced your web application or site. And which features would you like to see in <tt>@Anywhere</tt> in future releases?</p>
<h3>Further reading</h3>
<p>Have you been bitten by the <tt>@Anywhere</tt> bug? If so, here are some great places to find out more…</p>
<p style="text-align: center;"><a href="http://code.google.com/p/twitter-api/issues/list"><img class="size-medium wp-image-7215  aligncenter" src="http://thinkvitamin.com/wp-content/uploads/2010/09/googlecode.png" alt="" width="470" /></a></p>
<ul>
<li><a href="http://www.slideshare.net/toddkloots/anywhere/">http://www.slideshare.net/toddkloots/anywhere/</a></li>
<li><a href="http://platform.twitter.com/js-api.html">http://platform.twitter.com/js-api.html</a></li>
<li></li>
</ul>
<p>I also really like this integration of Twitter Hovercards into a WordPress blog comments</p>
<ul>
<li><a href="http://www.binarymoon.co.uk/2010/05/integrate-twitters-wordpress-comments/">http://www.binarymoon.co.uk/2010/05/integrate-twitters-wordpress-comments/</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/twitter-anywhere-revisited/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>HTML5 Video: Basic JavaScript Interaction [Video Tutorial]</title>
		<link>http://thinkvitamin.com/code/html5-video-basic-javascript-interaction-video-tutorial/</link>
		<comments>http://thinkvitamin.com/code/html5-video-basic-javascript-interaction-video-tutorial/#comments</comments>
		<pubDate>Tue, 10 Aug 2010 14:39:03 +0000</pubDate>
		<dc:creator>Keir Whitaker</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Videos]]></category>

		<guid isPermaLink="false">http://thinkvitamin.com/?p=6935</guid>
		<description><![CDATA[It&#8217;s Tuesday and time for our first visit of the week to the Think Vitamin Membership video library. Today Jim looks at implementing some basic HTML5 video controls via JavaScript. This video is just under 6 minutes long. Just a quick update to mention the fact that you can now view this video on your [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s Tuesday and time for our first visit of the week to the <a href="http://membership.thinkvitamin.com/">Think Vitamin Membership </a>video library. Today Jim looks at implementing some basic HTML5 video controls via JavaScript. This video is just under 6 minutes long.</p>
<p>Just a quick update to mention the fact that you can now view this video on your iPhone and iPad.</p>
<p><!-- Start of Brightcove Player --></p>
<div style="display:none">
</div>
<p><!--<br />
By use of this code snippet, I agree to the Brightcove Publisher T and C<br />
found at https://accounts.brightcove.com/en/terms-and-conditions/.<br />
--></p>
<p><script language="JavaScript" type="text/javascript" src="http://admin.brightcove.com/js/BrightcoveExperiences.js"></script></p>
<p><object id="myExperience90206759001" class="BrightcoveExperience"><param name="bgcolor" value="#FFFFFF" /><param name="width" value="705" /><param name="height" value="388" /><param name="playerID" value="89176682001" /><param name="playerKey" value="AQ%2E%2E,AAAAFEediwk%2E,2euW9ZlTxZAx4lLOZ1DtKcbmqEvxwq5q" /><param name="isVid" value="true" /><param name="isUI" value="true" /><param name="dynamicStreaming" value="true" /><param name="@videoPlayer" value="90206759001" /></object></p>
<p><!--<br />
This script tag will cause the Brightcove Players defined above it to be created as soon<br />
as the line is read by the browser. If you wish to have the player instantiated only after<br />
the rest of the HTML is processed and the page load is complete, remove the line.<br />
--><br />
<script type="text/javascript">brightcove.createExperiences();</script></p>
<p><!-- End of Brightcove Player --></p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/html5-video-basic-javascript-interaction-video-tutorial/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to Use jQuery Selectors [Tutorial Video]</title>
		<link>http://thinkvitamin.com/code/how-to-use-jquery-selectors-tutorial-video/</link>
		<comments>http://thinkvitamin.com/code/how-to-use-jquery-selectors-tutorial-video/#comments</comments>
		<pubDate>Thu, 03 Jun 2010 07:10:47 +0000</pubDate>
		<dc:creator>Ryan Carson</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Videos]]></category>

		<guid isPermaLink="false">http://carsonified.com/?p=6105</guid>
		<description><![CDATA[We&#8217;ve decided to release one more video from the Think Vitamin Membership Training Library for you guys :) It&#8217;s launching next week, so get ready! If you missed the Advanced CSS3 Box-Shadow video, feel free to check it out as well (the feedback has been amazing &#8211; everyone seems to love them). Here is a [...]]]></description>
			<content:encoded><![CDATA[<p>We&#8217;ve decided to release one more video from the <a href="http://membership.thinkvitamin.com">Think Vitamin Membership</a> Training Library for you guys :) It&#8217;s launching next week, so get ready!</p>
<p>If you missed the <a href="http://carsonified.com/blog/design/css3-design/advanced-css3-box-shadow-techniques">Advanced CSS3 Box-Shadow</a> video, feel free to check it out as well (the feedback has been amazing &#8211; everyone seems to love them).</p>
<p><img src="http://img.skitch.com/20100602-r5j3yt989s7nacfy46ktuw52wi.png" alt="Freeze frame from the intro of the video, showing a vitamins around the Think Vitamin Membership logo" /></p>
<p>Here is a seven minute video that will teach you how to use jQuery Selectors on your site. We will be adding 70+ videos like this <em>per month</em> to the Think Vitamin Membership Training Course Library. You can get access to all the videos for less than $1 per day.</p>
<p>The next 10 people to signup at <a href="http://membership.thinkvitamin.com">membership.thinkvitamin.com</a> will receive 50% off their first month. Yippee! :)</p>
<ul>
<li>View in HD</li>
<li>View on iPhone or Android</li>
<li>View on iPad</li>
</ul>
<p><img src="http://img.skitch.com/20100602-mhd1dcamsrf92rbni1dk5j4e9r.png" alt="screengrab from jQuery Selector video" /></p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/how-to-use-jquery-selectors-tutorial-video/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>John Resig on Advanced Javascript to Improve your Web App</title>
		<link>http://thinkvitamin.com/code/john-resig-on-advanced-javascript-to-improve-your-web-app/</link>
		<comments>http://thinkvitamin.com/code/john-resig-on-advanced-javascript-to-improve-your-web-app/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 10:54:29 +0000</pubDate>
		<dc:creator>Keir Whitaker</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://carsonified.com/?p=5394</guid>
		<description><![CDATA[In February 2010 John Resig, the creator and lead developer of the jQuery JavaScript library, spoke at the annual Future of Web Apps Miami conference. During this 25 minute talk John outlines many of the new features and ideas behind jQuery 1.4. A full transcript is available below. Watch this and other videos directly on [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://carsonified.com/?administer_redirect_7=http://futureofwebapps.com/dublin-2010/?utm_source=thinkvitamin&amp;utm_medium=banner&amp;utm_campaign=geoplanet"><img class=" alignnone" title="Future of Web Apps Dublin 2010" src="http://carsonified.com/wp-content/themes/carsonified/img/adverts/fowa_dublin_2010_side.jpg" alt="Future of Web Apps Dublin 2010" width="470" height="60" /></a></p>
<p>In February 2010 <a href="http://ejohn.org/">John Resig</a>, the creator and lead developer of the <a href="http://jquery.com">jQuery JavaScript library</a>, spoke at the annual <a href="http://futureofwebapps.com">Future of Web Apps</a> Miami conference. During this 25 minute talk John outlines many of the new features and ideas behind jQuery 1.4. A full transcript is available below.</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="470" height="264" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://vimeo.com/moogaloop.swf?clip_id=10593806&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=ff9933&amp;fullscreen=1" /><embed type="application/x-shockwave-flash" width="470" height="264" src="http://vimeo.com/moogaloop.swf?clip_id=10593806&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=ff9933&amp;fullscreen=1" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<p><a href="http://vimeo.com/channels/carsonifiedtv">Watch this and other videos directly on our Vimeo Channel</a><br />
<span id="more-5394"></span></p>
<h3>Transcript</h3>
<p>Thanks. I want to thank everyone for having me here today. I really appreciate it. I wanted to talk about a couple of things today, mostly around jQuery itself, but hopefully generic enough that in case you’re not using jQuery at least it will still be applicable to your web apps.</p>
<p>There are a couple of techniques I want to look at that hopefully all of you encounter when developing web applications. You always want to improve the performance of your JavaScript code. You always want to improve the accessibility, and you want to make your code simpler. Finally, you want to make the design process much easier.</p>
<p>When it comes to performance, there are a number of things in JavaScript, three of which are fairly easy, but especially so in jQuery. One is event delegation. Event delegation is a technique that routes around the traditional method of binding events. What I mean by that is typically when you attach a click handler to an element, you’re attaching a click to every single element that you want to attach to. This can be really costly. If you have a table with a couple of thousand table cells in it, that is going to be a lot of click handlers to attach.</p>
<p>Event delegation is whenever you attach a handler to some parent element up the tree, for example you attach it to the table itself rather than each individual table cell, and this takes advantage of the browser’s native event bubbling. What that means is when the user clicks on the table cell, the event will bubble up the tree, up to the table, and you can now handle the even there. That’s event delegation.</p>
<p>In this way, you only have to attach one event to the document, instead of a couple of thousand. It’s much faster and scales much better. jQuery provides a couple of methods for handling this; one is called [“dotlive”]. Another one is one that we just added the other day called “the delegate” method. What I think is really interesting about delegation is, in addition to it being much faster, it works in all current and all future elements as well. Even though there are only a thousand table cells to the document at the moment, if you add another thousand, it will continue to work on those as well. You don’t have to attach new handlers to handle them.</p>
<p>The delegate method is one that we just added the other day. This one embodies delegation at its very core. This is the exact example I was talking about. You’re attaching a click event to a core element, a root element such as the table. Then you’re watching for any (in this case) hovers over any table cell. It’s a very simple piece of code, and it gets you exactly what you want in the end.</p>
<p>Live events is a slightly different way of writing and doing delegation, but the nice thing is it works and appears to work in the same exact way as event binding does. You get to use the same syntax. You can use a selector, and then you can attach events directly to it, or seemingly directly to it. In the background, jQuery routes around and makes sure that it goes in all the right places.</p>
<p>For example, here we have these menus that when you mouse over, it does a little animation to toggle out the sub menu. The nice thing is if we add new menu, the animation will also work on the new one we just added. In this way, it’s live. It will continue to work with both current and future elements on the page.</p>
<p>Another technique is something you don’t necessarily have to do yourself, but it’s something that jQuery internalizes. It’s the ability of storing HTML fragments in DOM fragments. What this means is if you’re generating a piece of HTML on jQuery, an HTML string, we’re taking that and converting it to a number of DOM nodes, and sticking that in a DOM fragment.</p>
<p>What I mean by that is the DOM has this concept of, amongst other things, a document fragment. This fragment is sort of a very lightweight container for holding DOM nodes. You can put them in; it acts as a sort of collection. In this case, it’s a very simplified version of what we’re doing in jQuery core, which is if you want to take that HTML snippet and turn it into something held in a document fragment, we take it and enter HTML to generate some nodes. We extract those nodes back out and stick it in a fragment.</p>
<p>What’s interesting about a fragment is that you can perform operations using a fragment and they’re incredibly fast. What I mean by that is you can insert in an entire fragment into a document, but when you insert it, you’re not inserting the fragment itself but the nodes contained within the fragment. In this way, it’s very fast. We got some big speed ups by switching our code to this.</p>
<p>Also, we can now cache those fragments. If we have an HTML string that is coming in, and we’re generating a fragment out at the end, we can cache that result; we can cache the string to the fragment. We can use that and save having to regenerate that entire fragment again, and again. In this way, jQuery internalizes this and handles all that immediately.</p>
<p>Another technique that is good for performance, and is much larger than jQuery itself, is loading your JavaScript library from a CDN. A CDN is short for Content Delivery Network and what that effectively translates into is a bunch of geo-position datacenters around the globe. Not all of us have the finances to build a whole bunch of datacenters all around, but there are a number of great services that handle this. Amazon CloudFront is one of them. We use EdgeCast in jQuery, and MediaTemple is hosting EdgeCast. Additionally, many of the popular JavaScript libraries are also hosted by Google and Microsoft. They host them on their private CDNs as well.</p>
<p>What is really nice about the CDNs, in addition to being geo-positioned, is that the files are automatically minified and gzipped. Minifying and gzipping your JavaScript is the best way to serve your JavaScript code, absolutely. The very first step you should do when pushing JavaScript code into production is to run it through a minifier first. A typical minifier is like the recently released Google Closure or [0:49:21?], or tools like that. Those strip out all the white space, all the comments, all that stuff, and reduce your code down to the smallest possible code you can send to the browser.</p>
<p>Additionally, gzipping is something you can configure in your web server and this will compress your code even further. In the case of jQuery, we started out at just over 150K with raw script, but when we actually transmitted down, we were only sending about 20K with the code, since it’s been minified and gzipped along the way. This is a huge speed up and obviously, this is a big difference in the amount of data that we have to transmit. It saves us bandwidth and it loads faster for the users.</p>
<p>For improving accessibility, a lot of what can be done is working in a very unobtrusive manner. In this way, this is a generic technique that works in all of your JavaScripting, which is that when you override the way that a browser typically does something, for example submitting a form or clicking a link, you can then go through and implement your own functionality. This is effectively unobtrusive scripting. You’re taking something that works already, in a browser, and you layer on your own functionality.</p>
<p>jQuery makes this really easy in addition to providing techniques for handling that, but all your JavaScripts in jQuery code can be encapsulated in the “document ready event”. This event fires the instant your document is ready to be manipulated and traversed. This is very useful because, almost always, this event will fire before the page is visible to the user. You can get in there and make changes to the page, and change how it’s going to display. Then the user will see that modified result.</p>
<p>Probably the most basic example of doing unobtrusive scripting is overriding all links that are going to be clicked, and when they’re clicked we’re going to load the URL into the page itself. The central line here is “return false”, and in jQuery that is telling the browser to prevent the normal click action and we’re going to override it and do something else instead. In this case, clicking this link would normally take us to a different page, but now we click it instead and we load in that page and inject it into our document. In this case, loading and injecting is done with the jQuery load method.</p>
<p>One technique that can serve really well here is that jQuery provides an additional header in every single Ajax request that occurs. It’s called the “x requested with header”, so if you see in your code &#8211; this is a PHP snippet here, but it will be similar in any other language it uses. If you see that this header exists, you can then adapt your content to be displayed in a different manner. Maybe you’ll display in an XML or JSON or what have you. A better technique might be, if you want to load in an HTML fragment, is to strip off the header and footer of your page. That way you can dynamically request your page and only grab the inner contents. You can grab that and then inject it into your page.</p>
<p>One alternative to that is this additional trick in jQuery, which is a load method that I showed before; you can load in a file that you specify and grab the HTML contents from that file and inject it into a page. If you’ll note there, on the end, just after the file there is an H2. That is requesting the HTML file, serializing it into a DOM structure, and then searching and looking for all the H2 elements. This is really useful because you can then grab and load in chunks of a remote HTML document, and inject it into your site, without ever doing any server-side manipulation. In this way, as a front-end developer, you have an incredible amount of control over the content that you can grab and load to your page. I love this trick because I don’t ever have to touch the server in this case. It’s great.</p>
<p>Reducing complexity, at least in jQuery land, all relates to enhancing that relationship around the DOM element. jQuery provides a number of tools for making it easier to communicate through a DOM element. I’ll show you what I mean.</p>
<p>jQuery provide an API called the Data API. It provides this data method that you can use, to both access and set values on a DOM element. What’s interesting about this and what makes this different from accessing and getting DOM attributes, is that when you access and set DOM attributes, they’re visible; they’re permanently attached to the element itself, but what we’re doing in jQuery is we actually create a separate data store and store that separately, away from the element. Any time you set or get data on that element, you’re actually setting it in our data store. It’s very fast.</p>
<p>There are a lot of advantages to that. In jQuery, we use this central data store to store all the events that we bind to an element. Instead of attaching the handlers directly to the element itself, we store it in our separate data store. The nice thing about this is we can manage all the garbage collection issues surrounding Internet Explorer. What’s good about this is we have all our data in this separate store, and when the element is removed, we can handle that and clean up all the data we have there. In that way, you will be recapturing all the memory that is being used, every single time, instead of there being nasty memory leaks shooting all around, as want to happen in Internet Explorer.</p>
<p>Another cool thing we have implemented is if you set or get a data value, we trigger an event. You can override this event and implement new functionality. If you’re writing a plug-in where you’re looking for a specific value to be set or get, you can override that and implement your own values that should be set or get. This could be really cool. Then you use the Data API of setting and getting values for your plug-in.</p>
<p>This comes up to custom events. Custom events &#8211; what’s interesting in jQuery is we have the typical way of binding and triggering events, and it’s 100% identical to doing your own custom events, so if you have an event that is the name of your plug-in, or in this case my plug-in, it doesn’t matter; jQuery handles that identically and it works identically everywhere.</p>
<p>What’s nice about this is you can create and trigger your own events and use it as a way of communicating around the document. This is a bit different from the typical way in which you would see it triggered in a document, in that it’s not going to be triggered by a click; this is something you have to trigger manually. One thing that we have that is layered on top of this is the concept of event name spaces. Event name spaces allow you to, for example, attach a click or focus, but scoped within a particular name. In this case, we have a click that is within the scope within the name of a particular plug-in. What’s cool about this is you can then unbind all of the events that were bounded by a particular plug-in.</p>
<p>This is important because otherwise, the plug-in would have to maintain a list of all the handlers that is bound to any given element at any given time. That is very costly and something that we don’t want plug-in authors to have to worry about. This is something that you can handle completely just by giving all your handlers names.</p>
<p>In the end, what’s great is you can create these custom events as a way of communicating. The really nice thing about custom events in general is that it is a way of communicating from one-to-many, meaning that if you want to send a message, for example “remove”, you want to tell these DOM elements to remove, whenever that may occur; there could be any number of actions on the other end waiting to occur, based upon that trigger.</p>
<p>For example, here we have two different plug-ins that are both watching for a “remove” event to occur. They’ll both be triggered when the trigger runs. But, when you run the trigger, you don’t have to know that there are events actually bound. There could be zero events bound. There could be ten events bound. There could be any number and in that way it provides a very graceful way of coding. You can just trigger these events to occur, and it will just gracefully happen in your document.</p>
<p>jQuery also provides a way of doing what are called “special” events. These work at a more core, fundamental level compared to custom events. Special events are actually a complete way of implementing an event at a very core level. For example, if you want to simulate &#8211; at least in jQuery core, we use it to simulate the “submit” and “change” events in Internet Explorer. In Internet Explorer, those events are rather broken. We also use it to implement “mouse hunter”, “mouse leave”, “focus in” and “focus out” in all the other browsers.</p>
<p>Just to show you an example of what it takes, this is the total code to implement the focus in and focus out events in all browsers, except for IE. It’s actually very little code and it’s overriding the normal behavior so instead of attaching the handler to the document, we do it in a slightly different way.</p>
<p>One plug-in, for example, that makes use of this is a plug-in I wrote last night called “Hot Keys” where you can bind a key down, or a key up, or key press, and you can give a key combination. For example, when the key down one occurs on Ctrl A, do something. In this case, we’re returning false and that will prevent you from doing Ctrl A on the document, selecting everything presumably. You could also say Ctrl A and space Meta A to prevent on an Apple keyboard. This is the sort of thing you can do with special events.</p>
<p>A nice thing is being able to go in and simplify your design. What we provide in the jQuery project for that is jQuery UI. jQuery UI is a set of components and set of widgets that you can use, you can drop into your application, and they will just work. We designed them in a way that they’re not only easy to use but they have a really good API.</p>
<p>On top of that, they’re all themeable and customizable. I’ll show you an example here. You can completely customize them to the style of your website. This is the jQuery UI ThemeRoller. We can sort of see a selection here of jQuery UI components. For example, we have an accordion, a tabs widget, slider, date picker, dialog, progress bar, etc. These are all in jQuery UI core.</p>
<p>You can go in and you can actually start to customize that and load in other themes. We have a number of prebuilt themes. You can load in this orange-ish style. We can try this grayish style. There are different ones we have prebuilt, but what’s nice about this is you can go in and you can customize each of these things completely to your own desires.</p>
<p>If we didn’t like this particular header background and we wanted something different, we could go in and adapt the color to exactly what we wanted to see. Instead of this dark gray or something, maybe we want something much brighter. It will take that color, and actually generate all the CSS and all the images needed to view this theme, and give it to you in a single, nice, compressed CSS file right to the image file. And, it will work in all browsers, including IE6. We have all the alpha transparencies and everything already done.</p>
<p>I love this personally, because dealing with CSS cross-browser issues is absolutely the last thing I want to do. This is some way to route around that, that we’ve already taken care of all those problems and we’ve implemented in a very slick way. One cool thing about this is, for example, there is a number of jQuery plug-ins out there that are already themeable using the ThemeRoller, ones beyond jQuery UI.</p>
<p>For example, this is a jQuery plug-in called jqGrid. Since jqGrid is themeable with ThemeRoller, you can then load this tool called the ThemeRoller bookmarklet. I don’t remember the full name of it. You get this little panel, the same as what you would see in the ThemeRoller page. You can layer it on top of any page just using ThemeRoller. They’re using this bluish theme but let’s say we wanted a grid but we didn’t want that bluish theme; we wanted one that is more orange-ish. You can click it, load that theme dynamically and you can see how it will look, right inside the website. You can get there, tweak it to your heart’s content; you can tweak the header, colors, and everything. That will just work. That is something I find to be really cool.</p>
<p>What are we working on? In the jQuery project there are a few things we’re working on at the moment. We’re working on a better dynamic script loader that will do all sorts of dependency management. We’re working on a new templating engine so hopefully both of those will be coming up in new releases. We’re also working on a rewrite of the Ajax module, to become more extensible. And, perhaps the largest is that we’re working on good mobile support.</p>
<p>We want to make sure that not only is jQuery the best library for doing desktop web applications, but we want to make sure that same code base is the best library for doing mobile applications. To get there, we’re going to be testing against a whole bunch of mobile browsers on a number of different devices. I have a bunch of devices at home that I have set up and I’m already starting to go through them. We’re going to make sure that jQuery is going to work, not only in normal IE6, IE7, IE8, Opera, all the browsers, but it’s going to work in mobile IE, mobile Safari, Opera, all those mobile browsers, at least the ones that are feasible to implement jQuery on. This is something that we’re working on and we hope to make some very good progress here, very soon. There is some more information about the jQuery project if you have any questions, and I think I’m out of time but thank you all for having me today.</p>
<h3>Q + A</h3>
<p><strong>Ryan:</strong> Thank you very much. While we do the switchover we probably have about a minute for a question. Are there any questions for John?</p>
<p><strong>Q:</strong> Will jQuery support internationalization?</p>
<p><strong>John:</strong> jQuery core probably won’t but we already do some of that for jQuery UI. I think we’ve been talking about moving the validation plug-in, for example, into jQuery UI. The validation plug-in handles a lot of that stuff, especially number formatting. That is something, that and the addition of something like get text replacement that you can use for translating chunks of strings is another thing I’ve seen requested. Again, I don’t think either of those would be in jQuery core so much as probably jQuery UI. Most of those things typically relate to building a UI component, not a jQuery UI component, but a UI component in general.</p>
<p><strong>Ryan:</strong> We probably have time for another one.</p>
<p><strong>Q:</strong> The need to support Internet Explorer 6 and some of those older browsers, how much of that is holding back jQuery, and one day when you can get away from that, how much more capability do you think it will bring to jQuery?</p>
<p><strong>John:</strong> If we dropped support for IE6 today, absolutely nothing would change, at least for jQuery core. jQuery UI might be able to benefit more. The JavaScript engine and the DOM engine in their export did not change between 6 and 7. That is a bit of a lie. They did change. They introduced two bugs in IE7. It’s really frustrating. In our case, it would be better to drop IE7 support than IE6. The reality is that from my perspective, IE6 is the same as IE7. IE7 is shipping in IE8. IE8 is going to be around for a very long time. There is no reason to drop any of these.</p>
<p>You asked how much is this holding us back? At least for jQuery core, not &#8211; obviously we have to deal around all these browser issues, but it’s not degrading the performance of the code. We make sure, at the very least, that the code that we’re shipping is going to perform the best it can, regardless. You don’t have to worry about that. I think that’s the primary concern, does it affect my performance, if so, kill it with fire. The other one is can I save some bandwidth by extracting that. Obviously, we could save some file size by removal of that code, not a massive amount, but maybe a couple K. Again, I don’t think it’s holding us back.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/john-resig-on-advanced-javascript-to-improve-your-web-app/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Getting Started with Yahoo! GeoPlanet Explorer</title>
		<link>http://thinkvitamin.com/code/getting-started-with-yahoo-geoplanet-explorer/</link>
		<comments>http://thinkvitamin.com/code/getting-started-with-yahoo-geoplanet-explorer/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 13:00:04 +0000</pubDate>
		<dc:creator>Christian Heilmann</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://carsonified.com/?p=4883</guid>
		<description><![CDATA[Where are you and what is around you? Geolocation is a hot topic. Google just got the patent on geolocated advertising, mobile phones allow us to pinpoint ourselves on the planet and find things nearby and with augmented reality applications we can even find our way by filming our surrounding and finding hidden treasures by [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Where are you and what is around you?</strong></p>
<p>Geolocation is a hot topic. Google just got the patent on geolocated advertising, mobile phones allow us to pinpoint ourselves on the planet and find things nearby and with augmented reality applications we can even find our way by filming our surrounding and finding hidden treasures by moving our mobile around. Using geolocation as a developer is quite easy, you can do a few things:</p>
<ul>
<li>If you are building something in a social network, you can get the geographical location from the user&#8217;s profile.</li>
<li>If you work on a certain mobile platform (Android, WebOS, iPhone) you get APIs to detect the current location.</li>
<li>If that is not an option you can use the W3C geo location API in browsers that support it.</li>
<li>If everything else fails you can guess the visitor&#8217;s location from their IP number.</li>
</ul>
<h3>That is the where, but how to know what is around me?</h3>
<p>Knowing the location is one thing, but what if you want to know more about the area? What about the geographical hierarchy? What part of the city/country are you in and which other geographical and administrative areas are nearby?</p>
<p>All of this has been available for you for quite a while. The <a href="http://developer.yahoo.com/geo/geoplanet/">GeoPlanet API</a> and <a href="http://developer.yahoo.com/geo/geoplanet/data/">dataset</a> released by Yahoo! has been out for a while but did not quite get the love from the mainstream developer crowd it deserves. The geo hackers, on the other hand already love it to bits and helped make it more accurate by providing feedback.</p>
<p>To make it a bit easier for you to understand what the GeoPlanet API allows you to do, I&#8217;ve put together the <a href="http://isithackday.com/geoplanet-explorer/">GeoPlanet Explorer</a> &#8211; a tool that lets you explore all the GeoPlanet data in an interactive way:</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="470" height="375" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/mL3oei5UhgM&amp;hl=en_US&amp;fs=1&amp;rel=0&amp;color1=0x234900&amp;color2=0x4e9e00" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="470" height="375" src="http://www.youtube.com/v/mL3oei5UhgM&amp;hl=en_US&amp;fs=1&amp;rel=0&amp;color1=0x234900&amp;color2=0x4e9e00" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<p>The Geoplanet Explorer uses three tools: <a href="http://developer.yahoo.com/yql/">YQL</a> for accessing and filtering data, <a href="http://yuilibrary.com/projects/yui3/">YUI3</a> for the rich interaction and <a href="http://developer.yahoo.com/yui/grids/">CSS layout</a>, <a href="http://developer.yahoo.com/maps/ajax/">Yahoo Maps</a> for display and PHP to glue all of that together. You can get the <a href="http://github.com/codepo8/geoplanet-explorer">full source code on GitHub</a>.<span id="more-4883"></span></p>
<h3>Simplifying matters using woeid</h3>
<p>One big problem of geo location is ambiguity. If you have a location with latitude and longitude you can pinpoint it on the globe. You don&#8217;t know what it is though. The centre of a certain county, city and a point of interest could share the same latitude and longitude, but they are actually totally different things.</p>
<p>To fix this problem, Yahoo! a long time ago introduced the <a href="http://developer.yahoo.com/geo/geoplanet/guide/concepts.html">Where on Earth ID</a> (or short <tt>woeid</tt>) which is a number that defines a place with its geographical location and describes what it is. For example my neighbourhood in London has the <tt>woeid</tt> of <tt>36239</tt> and that means I can get the following information from it when querying the GeoPlanet API:</p>
<ul>
<li>Stoke Newington (Suburb):
<ul>
<li>Country: United Kingdom</li>
<li>WOEID: 36239</li>
<li>Administrative:
<ul>
<li>England (Country)</li>
<li>Greater London (County)</li>
</ul>
</li>
<li>Localities:
<ul>
<li>London (Town)</li>
<li>Stoke Newington (Suburb)</li>
</ul>
</li>
<li>Postal N16 (Postal Code)</li>
<li>Location (lat/lon): 51.561199, -0.082980</li>
<li>Bounding Box: NE 51.577190, -0.058070 SW 51.546692, -0.092380</li>
</ul>
</li>
</ul>
<p>The bounding box information is very useful for displaying this information on a map as it shows you which points need to be visible in order to see the whole place.</p>
<p>There is just something pretty about having a number instead of a lat/lon pair which is why <tt>woeid</tt> is rapidly becoming a standard. Flickr supported it for quite a while, Dopplr uses it under the hood, the Yahoo! Weather API understands it and soon Twitter will also use it for geolocating content in an unambiguous way (right now there is only support in the <a href="http://engineering.twitter.com/2010/02/woeids-in-twitters-trends.html">Twitter Trends API</a>).</p>
<h3>So how could you use this for your own products?</h3>
<p>There are a lot of ways you can use the geo tools by Yahoo! in your own solutions &#8211; by far the easiest is using YQL to access the data. This, for example allowed me to write the <a href="http://isithackday.com/hacks/geo/addmap.html">addmap.js</a> solution:</p>
<p><a href="http://isithackday.com/hacks/geo/addmap.html"><img src="http://farm5.static.flickr.com/4058/4408673432_e4f2cb178a.jpg" alt="Analyse text and add a map with its locations in pure JavaScript by  you." width="470" /></a></p>
<p>Using this you can can easily take the content of a page element with a certain ID and add a map of the locations it &#8220;talks about&#8221; to the document:</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">&lt;code&gt;&lt;script src=&quot;http://github.com/codepo8/geotoys/raw/master/addmap.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
addmap.config.mapkey = 'YOUR_API_KEY';
addmap.analyse<span class="br0">&#40;</span>'content'<span class="br0">&#41;</span>;
&lt;/script&gt;&lt;/code&gt;</pre></div></div>

<p>The API key is needed for the Google maps, not for YQL. YQL in this case under the hood uses <a href="http://developer.yahoo.com/geo/placemaker/">Placemaker</a> which is an API that finds geographical content in URLs or texts.</p>
<p>YQL and the geo tools offer you some other interesting options:</p>
<h3>Geographical locations in texts/urls/RSS feeds</h3>
<p>By using the Placemaker table in YQL you can extract geographical locations from a texts or a source on the web:</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">&lt;code&gt;select * from geo.placemaker where documentContent =
&quot;Hi, I am Chris, I live in London but actually I am from Germany&quot;
and documentType=&quot;text/plain&quot; and appid=&quot;&quot;&lt;/code&gt;</pre></div></div>

<p>This finds both &#8220;London&#8221; and &#8220;Germany&#8221; as geographical locations. You will find places and references. Places are what has been found and references where it was found. The <tt>start</tt> and <tt>end</tt> elements describe the character location in the whole string.</p>
<p>Placemaker also takes feed and web site URIs and finds the locations in them for you. For example to see the locations mentioned in my portfolio page you can do the following:</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">&lt;code&gt;select * from geo.placemaker where documentURL =
&quot;http://icant.co.uk&quot; and documentType=&quot;text/html&quot; and appid=&quot;&quot;&lt;/code&gt;</pre></div></div>

<p>Again, you can check the <a href="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placemaker%20where%20documentURL%20%3D%20%0A%22http%3A%2F%2Ficant.co.uk%22%20and%20documentType%3D%22text%2Fhtml%22%20and%20appid%3D%22%22&amp;format=xml&amp;env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys">result as an XML</a> file. As this is an HTML document there is no start and end but the references are reported as XPATHs.</p>
<p>Feeds are also supported, so if you want to get the locations in the BBC News feed you can use the following:</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">&lt;code&gt;select * from geo.placemaker where documentURL =
&quot;http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/front_page/rss.xml&quot;
and documentType=&quot;text/rss&quot; and appid=&quot;&quot;&lt;/code&gt;</pre></div></div>

<p>Verify the <a href="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placemaker%20where%20documentURL%20%3D%20%0A%22http%3A%2F%2Fnewsrss.bbc.co.uk%2Frss%2Fnewsonline_uk_edition%2Ffront_page%2Frss.xml%22%20%0Aand%20documentType%3D%22text%2Frss%22%20and%20appid%3D%22%22&amp;format=xml&amp;env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys">result as an XML</a> at your leisure &#8211; this time the XPATHs point to the RSS items.</p>
<p>The easiest way to see the power of Placemaker is using <a href="http://icant.co.uk/geomaker">GeoMaker</a> which gives you a simple interface to do turn a text or URL into a map or microformats to embed into your documents:</p>
<p><a href="http://icant.co.uk/geomaker"><img src="http://farm3.static.flickr.com/2559/3751595472_199877c7b2.jpg" alt="GeoMaker screenshot" width="470" /></a></p>
<h3>Location by IP</h3>
<p>Getting the geographical location of an IP is possible with the following YQL statement:</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">&lt;code&gt;select * from geo.places where woeid in <span class="br0">&#40;</span>
  select place.woeid from flickr.places where <span class="br0">&#40;</span>lat,lon<span class="br0">&#41;</span> in <span class="br0">&#40;</span>
    select Latitude,Longitude from ip.location where ip = &quot;123.23.23.33&quot;
  <span class="br0">&#41;</span>
<span class="br0">&#41;</span>&lt;/code&gt;&lt;span style=&quot;font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 19px; white-space: normal; font-size: 13px;&quot;&gt;What we're doing here is using the &lt;a href=&quot;http://www.ip2location.com/&quot;&gt;IP2location API &lt;/a&gt;,get the woeid from the latitude and longitude using the &lt;a href=&quot;http://www.flickr.com/services/api/flickr.places.findByLatLon.html&quot;&gt;Flickr &lt;tt&gt;findByLatLon&lt;/tt&gt; method&lt;/a&gt; and run the result through the &lt;a href=&quot;http://developer.yahoo.com/geo/geoplanet/guide/api_docs.html&quot;&gt;geo API&lt;/a&gt; to get all the information - quite some work off your hands, isn't it? Without YQL you'd have to sign up for all these APIs and understand their inner workings to get the same information.&lt;/span&gt;</pre></div></div>

<p>Getting location by IP is an old trick in the book of advertisers &#8211; you probably will have encountered ads like &#8220;meet singles in <em>your city</em> now&#8221; and see them changing when you went to another place &#8211; this is what they use to get this information. The accuracy of IP location is not very high though. It also can feel a bit creepy.</p>
<h3>Location by Latitude and Longitude</h3>
<p>Therefore it is much better to use a system that allows people to opt-in to tell their geographical location. There are services for that but we also have a <a href="http://dev.w3.org/geo/api/spec-source.html">W3C API</a> built into browsers. Right now Firefox and Mobile Safari support it but it also cropped up in the latest <a href="http://www.wait-till-i.com/2010/03/04/google-chrome-getting-navigator-geolocation/">developer build of Chrome</a>.</p>
<p>Using the W3C location API is easy:</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">&lt;code&gt;&lt;script&gt;
if<span class="br0">&#40;</span>navigator.geolocation<span class="br0">&#41;</span><span class="br0">&#123;</span>
  navigator.geolocation.getCurrentPosition<span class="br0">&#40;</span>function<span class="br0">&#40;</span>position<span class="br0">&#41;</span><span class="br0">&#123;</span>
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    alert<span class="br0">&#40;</span>'you are at' + lat +','+lon<span class="br0">&#41;</span>;
  <span class="br0">&#125;</span>,function<span class="br0">&#40;</span>error<span class="br0">&#41;</span><span class="br0">&#123;</span>
    alert<span class="br0">&#40;</span>'Couldn\'t get your location :<span class="br0">&#40;</span>'<span class="br0">&#41;</span>;
  <span class="br0">&#125;</span><span class="br0">&#41;</span>;
<span class="br0">&#125;</span>
&lt;/script&gt;&lt;/code&gt;</pre></div></div>

<p>You test if the browser supports <tt>navigator.geolocation</tt> and if it does you use the <tt>getCurrentPosition()</tt> method to retrieve the current position. This will cause the browser to ask the visitor if they want to share their information &#8211; normally in an information bar on top of the viewport as shown in this screenshot:</p>
<p><a title="Security popup triggered by navigator.geolocation by codepo8, on Flickr" href="http://www.flickr.com/photos/codepo8/4408578132/"><img style="border: 1px solid #999;" src="http://farm5.static.flickr.com/4068/4408578132_73bcb575c6.jpg" alt="Security popup triggered by navigator.geolocation" width="470" /></a></p>
<p>The <tt>getCurrentPosition()</tt> method takes two parameters which are function to call in the success and the failure case &#8211; meaning that the visitor allowed you to get their location or not &#8211; or that there was some other error.</p>
<p>You can then use YQL once more to get the location from latitude and longitude &#8211; this time using the Flickr API method as the first one:</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">&lt;code&gt;select * from geo.places where woeid in <span class="br0">&#40;</span>
  select place.woeid from flickr.places where lat=<span style="">51.5142271</span> and lon=-<span style="">0.1289602</span>
<span class="br0">&#41;</span>&lt;/code&gt;</pre></div></div>

<p>See the <a href="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20woeid%20in%20(%0A%20%20select%20place.woeid%20from%20flickr.places%20where%20lat%3D51.5142271%20and%20lon%3D-0.1289602%0A)&amp;format=xml&amp;env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys">XML output here</a>.</p>
<h3>Putting it all together</h3>
<p>Let&#8217;s end with an example script how you can use this. We use the W3C geolocation API to get a visitor&#8217;s location and if it isn&#8217;t available we fall back to using the IP. In any case, we use YQL to get the location information and the areas around the current location. The solution uses JavaScript except for retrieving the IP which is done in this case by PHP. You can see the full <a href="http://isithackday.com/hacks/geo/geotest.php">demo in action here</a>. See the comments <tt>//</tt> for information about what is going on.</p>

<div class="wp_syntax"><div class="code"><pre class="" style="font-family:monospace;">&lt;code&gt;&lt;script type=&quot;text/javascript&quot; charset=&quot;utf-<span style="">8</span>&quot;&gt;
&lt;?php
  if <span class="br0">&#40;</span>$_SERVER<span class="br0">&#91;</span>'HTTP_X_FORWARD_FOR'<span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
   $ip = $_SERVER<span class="br0">&#91;</span>'HTTP_X_FORWARD_FOR'<span class="br0">&#93;</span>;
  <span class="br0">&#125;</span> else <span class="br0">&#123;</span>
   $ip = $_SERVER<span class="br0">&#91;</span>'REMOTE_ADDR'<span class="br0">&#93;</span>;
  <span class="br0">&#125;</span>
  if<span class="br0">&#40;</span>preg_match<span class="br0">&#40;</span>'/^<span class="br0">&#91;</span>\d+\.?<span class="br0">&#93;</span>+$/',$ip<span class="br0">&#41;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
    echo 'var IP = &quot;' . $ip . '&quot;';
  <span class="br0">&#125;</span>
?&gt;
&nbsp;
// ^^
// This PHP block will get the current IP and assign it to a JavaScript
// variable - if it is the right format.
&nbsp;
if<span class="br0">&#40;</span>navigator.geolocation<span class="br0">&#41;</span><span class="br0">&#123;</span>
  navigator.geolocation.getCurrentPosition<span class="br0">&#40;</span>
    function<span class="br0">&#40;</span>position<span class="br0">&#41;</span><span class="br0">&#123;</span>
      getDataForLatLon<span class="br0">&#40;</span>position.coords.latitude,
                       position.coords.longitude<span class="br0">&#41;</span>;
    <span class="br0">&#125;</span>,
    function<span class="br0">&#40;</span>error<span class="br0">&#41;</span><span class="br0">&#123;</span>
      if<span class="br0">&#40;</span>IP<span class="br0">&#41;</span><span class="br0">&#123;</span>
        getFromIP<span class="br0">&#40;</span>IP<span class="br0">&#41;</span>;
      <span class="br0">&#125;</span>
    <span class="br0">&#125;</span><span class="br0">&#41;</span>;
<span class="br0">&#125;</span> else<span class="br0">&#123;</span>
  if<span class="br0">&#40;</span>IP<span class="br0">&#41;</span><span class="br0">&#123;</span>
    getFromIP<span class="br0">&#40;</span>IP<span class="br0">&#41;</span>;
  <span class="br0">&#125;</span>;
<span class="br0">&#125;</span>
&nbsp;
// ^^
// we test if the W3C location API is supported and if it is, we
// get the current lat and lon and call the appropriate method.
// if there was an error or the API is not available at all we call
// getFromIP.
&nbsp;
function load<span class="br0">&#40;</span>yql,cb<span class="br0">&#41;</span><span class="br0">&#123;</span>
  var src = 'http://query.yahooapis.com/v1/public/yql?q='+
            encodeURIComponent<span class="br0">&#40;</span>yql<span class="br0">&#41;</span> + '&amp;format=json&amp;callback=' + cb + '&amp;'+
            'env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
  var head = document.getElementsByTagName<span class="br0">&#40;</span>'head'<span class="br0">&#41;</span><span class="br0">&#91;</span><span style="">0</span><span class="br0">&#93;</span>;
  var s = document.createElement<span class="br0">&#40;</span>'script'<span class="br0">&#41;</span>;
  s.setAttribute<span class="br0">&#40;</span>'src',src<span class="br0">&#41;</span>;
  head.appendChild<span class="br0">&#40;</span>s<span class="br0">&#41;</span>;
<span class="br0">&#125;</span>
&nbsp;
// ^^
// YQL is a web service that returns JSON. This allows us to create
// script nodes dynamically to get information from it. This function
// does that for us.
&nbsp;
function getDataForLatLon<span class="br0">&#40;</span>lat,lon<span class="br0">&#41;</span><span class="br0">&#123;</span>
  var yql = 'select * from geo.places where woeid in <span class="br0">&#40;</span>'+
            'select place.woeid from flickr.places where lat='+
            lat + ' and  lon=' + lon + '<span class="br0">&#41;</span>';
  load<span class="br0">&#40;</span>yql,'foundLocation'<span class="br0">&#41;</span>;
<span class="br0">&#125;</span>
function foundLocation<span class="br0">&#40;</span>o<span class="br0">&#41;</span><span class="br0">&#123;</span>
  if<span class="br0">&#40;</span>o.query.results<span class="br0">&#41;</span><span class="br0">&#123;</span>
    var place = o.query.results.place
    var out = '&lt;p&gt;You are in ' + place.name + ' which is a '+
               place.placeTypeName.content + ' located at <span class="br0">&#40;</span>'+
               place.centroid.latitude + ',' + place.centroid.longitude+
               '<span class="br0">&#41;</span>&lt;/p&gt;';
    document.getElementById<span class="br0">&#40;</span>'location'<span class="br0">&#41;</span>.innerHTML = out;
    getBelongTos<span class="br0">&#40;</span>place.woeid<span class="br0">&#41;</span>;
  <span class="br0">&#125;</span>
<span class="br0">&#125;</span>
&nbsp;
// ^^
// If we can get a lat and lon from the API, we put together the right
// YQL statement. If we are successful we call the foundLocation<span class="br0">&#40;</span><span class="br0">&#41;</span> method
// which writes out the right HTML to the document and calls the
// getBelongTos<span class="br0">&#40;</span><span class="br0">&#41;</span> method
&nbsp;
function getFromIP<span class="br0">&#40;</span>ip<span class="br0">&#41;</span><span class="br0">&#123;</span>
  var yql = 'select * from geo.places where woeid in <span class="br0">&#40;</span>'+
            'select place.woeid from flickr.places where <span class="br0">&#40;</span>lat,lon<span class="br0">&#41;</span> in<span class="br0">&#40;</span>'+
            'select Latitude,Longitude from ip.location'+
            ' where ip=&quot;'+ip+'&quot;<span class="br0">&#41;</span><span class="br0">&#41;</span>';
  load<span class="br0">&#40;</span>yql,'foundLocation'<span class="br0">&#41;</span>;
<span class="br0">&#125;</span>
&nbsp;
// ^^
// If there was no luck with the W3C geo API we call this function using
// the IP we got from PHP
&nbsp;
function getBelongTos<span class="br0">&#40;</span>woeid<span class="br0">&#41;</span><span class="br0">&#123;</span>
  var yql = 'select * from geo.places.belongtos<span class="br0">&#40;</span><span style="">0</span><span class="br0">&#41;</span> where '+
            'member_woeid='+woeid;
  load<span class="br0">&#40;</span>yql,'foundBelongs'<span class="br0">&#41;</span>;
<span class="br0">&#125;</span>
function foundBelongs<span class="br0">&#40;</span>o<span class="br0">&#41;</span><span class="br0">&#123;</span>
  if<span class="br0">&#40;</span>o.query.results<span class="br0">&#41;</span><span class="br0">&#123;</span>
    var out = '&lt;p&gt;Your location belongs to: ';
    var place = o.query.results.place;
    var info = <span class="br0">&#91;</span><span class="br0">&#93;</span>;
    for<span class="br0">&#40;</span>var i=<span style="">0</span>;i&lt;place.length;i++<span class="br0">&#41;</span><span class="br0">&#123;</span>
      var cur = place<span class="br0">&#91;</span>i<span class="br0">&#93;</span>;
      info.push<span class="br0">&#40;</span>cur.name + ' <span class="br0">&#40;</span>' + cur.placeTypeName.content + '<span class="br0">&#41;</span>'<span class="br0">&#41;</span>;
    <span class="br0">&#125;</span>
    var out = '&lt;p&gt;Your location belongs to: ' + info.join<span class="br0">&#40;</span>', '<span class="br0">&#41;</span> + '&lt;/p&gt;';
    document.getElementById<span class="br0">&#40;</span>'location'<span class="br0">&#41;</span>.innerHTML += out;
  <span class="br0">&#125;</span>
<span class="br0">&#125;</span>
&nbsp;
// ^^
// If we found a location, then we call the belongtos method of the
// GeoPlanet API to get all the areas the current location belongs to.
&nbsp;
&lt;/script&gt;&lt;/code&gt;</pre></div></div>

<p>In my case the result from the W3C geo location is:</p>
<blockquote><p>You are in St. Giles&#8217;s which is a Suburb located at (51.516151,-0.125460)</p>
<p>Your location belongs to: WC1V 6 (Postal Code), London Borough of Camden (Local Administrative Area), 0207 London (Zone), Middlesex (Historical County), London (Town), Greater London (County), MMA London (MMA), South East England (Colloquial), DMA South East England (DMA), England (Country), England and Wales (Colloquial), Great Britain (Colloquial), United Kingdom (Country), Market United Kingdom and Ireland (Market), Europe/London (Time Zone), British Isles (Supername), Northern Europe (Supername), European Union (Supername), Western Europe (Supername), Europe (Continent), Eurasia (Supername), Earth (Supername)</p></blockquote>
<p>Only using IP I get:</p>
<blockquote><p>You are in Whitehall which is a Suburb located at (51.501831,-0.125760)</p>
<p>Your location belongs to: SW1A 2 (Postal Code), Westminster (Suburb), City of Westminster (Local Administrative Area), 0207 London (Zone), Middlesex (Historical County), London (Town), Greater London (County), MMA London (MMA), South East England (Colloquial), DMA South East England (DMA), England (Country), England and Wales (Colloquial), Great Britain (Colloquial), United Kingdom (Country), Market United Kingdom and Ireland (Market), Europe/London (Time Zone), British Isles (Supername), Northern Europe (Supername), European Union (Supername), Western Europe (Supername), Europe (Continent), Eurasia (Supername), Earth (Supername)</p></blockquote>
<p>Quite a lot of information using a few lines of code, isn&#8217;t it? Geographical location is a very interesting topic and allows us to show much more useful content to our visitors. Using YQL and GeoPlanet it is pretty easy for you to do so &#8211; give it a go!</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/getting-started-with-yahoo-geoplanet-explorer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Client Side Code Highlighting Made Easy</title>
		<link>http://thinkvitamin.com/code/client-side-code-highlighting-made-easy/</link>
		<comments>http://thinkvitamin.com/code/client-side-code-highlighting-made-easy/#comments</comments>
		<pubDate>Thu, 05 Nov 2009 15:16:11 +0000</pubDate>
		<dc:creator>Keir Whitaker</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://carsonified.com/?p=3659</guid>
		<description><![CDATA[I have recently been working on a little out of hours PHP project called &#8220;Dummy&#8220;. The code is almost complete, apart from the obligatory prettifying of indents and comments, which means it&#8217;s time to turn my attention to the online documentation. As part of the &#8220;How to Use&#8221; page I need to show small PHP [...]]]></description>
			<content:encoded><![CDATA[<p>I have recently been working on a little out of hours PHP project called &#8220;<em>Dummy</em>&#8220;. The code is almost complete, apart from the obligatory prettifying of indents and comments, which means it&#8217;s time to turn my attention to the online documentation.</p>
<p>As part of the &#8220;How to Use&#8221; page I need to show small PHP code examples. I also want them to look very readable and be easy to copy and paste. Hand cranking each code snippet using &lt;span&gt;&#8217;s, spaces and CSS clearly isn&#8217;t the way to go, there has to be an easy way.<span id="more-3659"></span></p>
<p><strong>Server Side Options</strong></p>
<p>Having used <a href="http://pygments.org/">Pygments</a> (a Python syntax highlighter) I had a quick look for PHP server side solutions and found two native PHP functions that could work.</p>
<ol>
<li><a href="http://php.net/manual/en/function.highlight-string.php">highlight_string();</a></li>
<li><a href="http://www.php.net/manual/en/function.highlight-file.php">highlight_file();</a></li>
</ol>
<p>Both produce HTML representations of the PHP code passed to them. However if you need to display JavaScript, HTML or CSS the output will be plain black text, albeit spaced and indented in the way that it was passed to the function. You will also need to deal with escaping certain characters in certain situations and a distinct separation between your HTML template and your code examples.</p>
<p><strong>Client Side Options</strong></p>
<p>My preferred approach would be to include the code examples in the HTML templates and use CSS to make them readable. After a quick <a href="http://www.google.com/search?ie=UTF-8&amp;oe=UTF-8&amp;sourceid=navclient&amp;gfns=1&amp;q=css+syntax+highlighter">Google search</a> I came across <a href="http://alexgorbatchev.com/wiki/SyntaxHighlighter">SyntaxHighlighter</a> by Alex Gorbatchev. It&#8217;s a JavaScript and CSS solution thats&#8217;s fully featured, easy to implement and degrades nicely.</p>
<p>Here&#8217;s an example of a PHP code snippet using SyntaxHighlighter</p>
<p><img style="border: 1px solid black;" title="php_syntax" src="/wp-content/uploads/2009/11/php_syntax.png" alt="php_syntax" width="470" height="223" /></p>
<p>It works by including a few JavaScript and CSS files in your HTML template. You can customise the CSS or use one of the seven themes provided.</p>
<p>In order to apply highlighting to a section of HTML it&#8217;s recommended to wrap your example in &lt;pre&gt; tags to preserve the formatting. The final stage is to apply a pre-defined relevant CSS class to the &lt;pre&gt; tag.</p>
<p>For example if we wanted our example to be highlighted as PHP we would add <strong>class=&#8221;brush: php;&#8221; </strong>to the &lt;pre&gt; tag. To turn it into a JavaScript example we would add <strong>class=&#8221;brush: jscript;&#8221;</strong>.</p>
<p>I have set up an <a href="http://carsonified.com/libs/syntaxhighlighter/">example page</a> which shows HTML, CSS, JavaScript, PHP and XML highlighting in action. View the source to see how easy it is to implement.</p>
<p>There&#8217;s support for a huge list of languages including:</p>
<ul>
<li>ActionScript3</li>
<li>Bash/shell</li>
<li>C#</li>
<li>C++</li>
<li>CSS</li>
<li>Delphi</li>
<li>Diff</li>
<li>Groovy</li>
<li>JavaScript</li>
<li>Java</li>
<li>JavaFX</li>
<li>Perl</li>
<li>PHP</li>
<li>Plain Text</li>
<li>PowerShell</li>
<li>Python</li>
<li>Ruby</li>
<li>Scala</li>
<li>SQL</li>
<li>Visual Basic</li>
<li>XML</li>
</ul>
<p>SyntaxHighlighter also provides a nice pop up tool-tip (look at the right hand side of a code example when hovering over it) enabling you to view the code in a blank page, copy it to the clipboard or print it.</p>
<p>There are undoubtedly other solutions out there, if you have a preferred one that works for you please link it up in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://thinkvitamin.com/code/client-side-code-highlighting-made-easy/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 1.169 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-02-10 03:28:19 -->

