<?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>The True Tribe &#187; Search Results  &#187;  javascript number</title>
	<atom:link href="http://www.thetruetribe.com/?s=javascript+number&#038;feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.thetruetribe.com</link>
	<description>Vroom! That&#039;s us leaving IE in the dust.</description>
	<lastBuildDate>Fri, 22 Jan 2010 23:34:03 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Understanding Pointers in JavaScript</title>
		<link>http://www.thetruetribe.com/2010/01/understanding-pointers-in-javascript/</link>
		<comments>http://www.thetruetribe.com/2010/01/understanding-pointers-in-javascript/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 09:10:29 +0000</pubDate>
		<dc:creator>jdempcy</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.thetruetribe.com/?p=298</guid>
		<description><![CDATA[Pointers can sometimes be a confusing topic. In JavaScript, it is perhaps even moreso than in other languages. The confusion arises because the var keyword is serving double duty. It is used to define variables, as is commonly realized. But it is also used to make references&#8211; or point to&#8211; other variables, functions and properties.
In [...]]]></description>
			<content:encoded><![CDATA[<p>Pointers can sometimes be a confusing topic. In JavaScript, it is perhaps even moreso than in other languages. The confusion arises because the <em>var</em> keyword is serving double duty. It is used to define variables, as is commonly realized. But it is also used to make references&#8211; or point to&#8211; other variables, functions and properties.<span id="more-298"></span></p>
<p>In most programming languages, for example  C, pointers are symbolized with an asterisk. JavaScript relies on the developer to know which <em>var</em>s are references and which aren&#8217;t. Why is this important? To put it succinctly, it is the difference between a variable being immutable or dynamic.</p>
<p>An example may be in order. Here&#8217;s a simple script you can paste into Firebug to see how pointers work.</p>
<pre>var marxBros = ['Chico', 'Harpo', 'Groucho']
var marxBrosPointer = marxBros;
marxBrosPointer.push('Zeppo');
console.log(marxBros); // ['Chico', 'Harpo', 'Groucho', 'Zeppo']
console.log(marxBrosPointer); // ['Chico', 'Harpo', 'Groucho', 'Zeppo']</pre>
<p>As you can see, <em>marxBros</em> and <em>marxBrosPointer</em> are identical. Anything you do to <em>marxBrosPointer</em> will change <em>marxBros </em>and vice versa. You can think of them like aliases which both reference the same thing.</p>
<p>There is actually no difference now. <em>marxBros</em> is the original and <em>marxBrosPointer</em> is the pointer. But, for all intents and purposes, they are identical. One thing to note is that if you reassign one of them to something else, it does not affect the other.</p>
<pre>var marxBros = ['Chico', 'Harpo', 'Groucho']
var marxBrosPointer = marxBros;
marxBros = null;
console.log(marxBrosPointer); //  ["Chico", "Harpo", "Groucho"]
</pre>
<p>Now let&#8217;s look at a case where we are not dealing with pointers. Let&#8217;s do the same thing as our first example, but instead of using an array, we&#8217;ll use strings. Yes, this makes a big difference.</p>
<pre>var marxBros = 'Chico, Harpo, Groucho';
var marxBrosCopy = marxBros;
marxBrosCopy += ', Zeppo';
console.log(marxBros); // 'Chico, Harpo, Groucho'
console.log(marxBrosCopy); // 'Chico, Harpo, Groucho, Zeppo'
</pre>
<p>When using strings instead of arrays, we find that changes to one do not change the other. Whether you change the original or the copy, they are not linked in the same way arrays and objects are. In the first example, changing either the original or the pointer resulted in changes to both variables. In this case, because strings are immutable in JavaScript, the <em>var</em> keyword copies a string instead of referencing it.</p>
<p>The same is true of numbers:</p>
<pre>var numberOfMarxBros = 3;
var numberOfMarxBrosCopy = numberOfMarxBros;
++numberOfMarxBrosCopy;
console.log(numberOfMarxBros); // 3
console.log(numberOfMarxBrosCopy); // 4
</pre>
<p>Compare this to properties and functions, which use pointers:</p>
<pre>// First let's make a cleanHouse function which has an action property
var cleanHouse = function() {
 console.log(arguments.callee.action);
}
cleanHouse.action = 'Doing your dishes...';

// Let's test and make sure it works as expected.
cleanHouse(); // 'Doing your dishes'

// So far so good. Now let's make a pointer to this function.
var actionToTake = cleanHouse;
actionToTake(); // 'Doing your dishes...'

// Now actionToTake is identical to cleanHouse. Any changes to one affect the other.
cleanHouse.action = 'Vacauuming the rug...';
actionToTake(); // 'Vacauuming the rug...'

actionToTake.action = 'Watering the plants...';
cleanHouse(); // 'Watering the plants...';
</pre>
<p>Here&#8217;s an example where the reference is lost and it does not achieve the goal:</p>
<pre>var cleanHouse = function() {
    console.log('Doing your dishes...');
}

var actionToTake = cleanHouse;

actionToTake(); // 'Doing your dishes...'

// Off to a good start, but here's where it goes wrong:

cleanHouse = function() {
    console.log('Vacauuming the rug...');
};

// Now the reference has been broken and actionToTake no longer refers to cleanHouse.
// Instead, actionToTake refers to, literally, the anonymous function that cleanHouse previously referred to.

actionToTake(); // 'Doing your dishes...'

// cleanHouse now refers to a new separate function.
cleanHouse(); // 'Vacuuming the rug...'
</pre>
<p>As you can see, it&#8217;s important to know how to use pointers. It will help you decide when you need a copy or something, or when you need a reference to it.</p>
<p>Feel free to post clarifications or other explanations. This topic is certainly important to becoming an advanced JavaScript developer, yet it is not addressed too often. I think we could all benefit from more clarity on the subject, myself included.</p>
<p>I hope this article has helped shine some light on this issue. Happy coding!</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.thetruetribe.com%2F2010%2F01%2Funderstanding-pointers-in-javascript%2F&amp;linkname=Understanding%20Pointers%20in%20JavaScript"><img src="http://www.thetruetribe.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.thetruetribe.com/2010/01/understanding-pointers-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Best of 2009, Ruby on Rails Edition</title>
		<link>http://www.thetruetribe.com/2010/01/best-of-2009-ruby-on-rails-edition/</link>
		<comments>http://www.thetruetribe.com/2010/01/best-of-2009-ruby-on-rails-edition/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 06:13:31 +0000</pubDate>
		<dc:creator>jdempcy</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[git]]></category>

		<guid isPermaLink="false">http://www.thetruetribe.com/?p=267</guid>
		<description><![CDATA[It was a good year for Rails. In 2009, we saw a number of exciting developments and a lot of great tools were released. Rails 2.3 was released in March 2009 and met with much fanfare. Rails has seen the introduction of templates, engines and a lot of other great features. 
Thanks to the popularity [...]]]></description>
			<content:encoded><![CDATA[<p>It was a good year for Rails. In 2009, we saw a number of exciting developments and a lot of great tools were released. Rails 2.3 was released in March 2009 and met with much fanfare. Rails has seen the introduction of templates, engines and a lot of other great features. <span id="more-267"></span></p>
<p>Thanks to the popularity of high profile websites that use Rails such as Hulu and Twitter, it is now considered a viable option for large sites. This kind of exposure means a lot of new development and movement. Rails seems to have outgrown many of the scaling woes of yesteryear. Now that it&#8217;s recognized in the mainstream as a stable and feature-rich platform for making websites, adoption has taken off, which means more tutorials, more resources, less bugs, lower barrier to entry and an overall better experience all around.</p>
<p>Another great development occurred quite recently in the Rails community. Two days before Christmas, on December 23, 2009, it was announced that <a href="http://en.wikipedia.org/wiki/Merb">Merb</a> would be merged into Rails 3. This is another huge development which will end the duplication of efforts and fracturing of the developer community that occurred due to competition between Merb and Rails.</p>
<p>In the spirit of celebrating this current Rails renaissance, here are some of the best Rails resources we&#8217;ve come across in the past year. We hope you find these as useful as we did!</p>
<h3><a href="http://lesscss.org/">Less CSS</a></h3>
<p><a href="http://www.thetruetribe.com/wp-content/uploads/2010/01/less-logo.png"><img class="alignnone size-full wp-image-271" title="less-logo" src="http://www.thetruetribe.com/wp-content/uploads/2010/01/less-logo.png" alt="" width="199" height="81" /></a></p>
<p>Less is an extension for CSS that allows you to use variables, perform operations such as mathematical calculations  and other neat features. It uses a Ruby script to read the .less file and generate a .css file to serve up to the browser.</p>
<p>Having variables is hugely helpful and it seems like an oversight in the CSS spec that it wasn&#8217;t included to begin with. Also, being able to add modifiers is nice. You can add, subtract, multiply, divide and even change colors. For instance, #FF0 + #00F would equal #FFF.</p>
<p>They also have mix-ins, which are classes that you can include in selectors, and it will include all of the properties from that class. This is the same thing functionally as adding that class to the elements matched by the selector, but without going into the HTML code. Mix-ins aren&#8217;t allowing us to do anything new that we couldn&#8217;t do already by adding the classes in HTML, but now it allows us to do this in CSS, without even touching the HTML. Some people will like this feature, others will deplore it&#8211; after all, we have a perfectly functional system where we can add multiple classes to a given element to achieve the same effect. But, I for one feel that this is a very useful feature to have. This is great for its reuse of code, and I love making modular CSS classes (for example, &#8220;rounded-corners&#8221;) that can be mixed into other CSS selectors.</p>
<h3><a href="http://git-scm.com/">Git</a> and <a href="http://github.com/">GitHub</a>, Social Coding</h3>
<p><a href="http://git-scm.com/"><img class="alignnone size-full wp-image-269" title="200px-Git-logo.svg" src="http://www.thetruetribe.com/wp-content/uploads/2010/01/200px-Git-logo.svg_.png" alt="git" width="200" height="73" /></a></p>
<p>These are two of the most useful tools of the year, hands down. Git caused a paradigm shift in distributed development. GitHub has become the de facto standard for Git hosting. If you&#8217;re unfamiliar with Git, read up on <a href="http://en.wikipedia.org/wiki/Git_%28software%29">the Wikipedia page</a>. To summarize, it&#8217;s a code versioning system that is well-suited for distributed development groups and open source software. It encourages users to make a fork of the repository so that any useful bug fixes, additions and changes can be easily merged back in, should the developers so desire.</p>
<p><a href="http://github.com/"><img class="alignnone size-full wp-image-270" title="github" src="http://www.thetruetribe.com/wp-content/uploads/2010/01/github.png" alt="github" width="100" height="45" /></a></p>
<p>I don&#8217;t see the advantage of using Git for personal projects or small in-house projects, but it is wonderful for open source efforts like Rails. It&#8217;s certainly a fine choice for any project, though I don&#8217;t see a big advantage over, say, Subversion, until you get into large scale distributed development situations like open source projects. Once you&#8217;re looking at open source projects, like those hosted on GitHub, we&#8217;re talking about a paradigm shift in efficiency.</p>
<p>Historically, most people would download zipped packages of code. Git encourages forking the repository instead. Let&#8217;s look at a quick example of how this works with Rails plugins.</p>
<p>Typically you could install a plugin by downloading some files somewhere and installing them, either with a script or by decompressing them directly to your vendor directory. This works fine but is unidirectional &#8212; you can only get the file from the developer, there is never an opportunity to submit code back, say, if you fix a bug.</p>
<p>The paradigm shift in efficiency that Git brings about is closing the loop: it allows you to easily submit code back to the trunk, thus capturing all those useful improvements to the code that would otherwise be lost on so many hard drives.</p>
<p>With GitHub, instead of downloading the Rails plugin, you fork the Git repositor to your vendor directory. Then, if you have to make changes to the plugin (which I almost always have to do, despite my best efforts to avoid it), you still retain the ability to update the code without losing your fixes. The old way was that if I wanted to upgrade a plugin that I had customized, I would have to download the new one and then manually go through and make whatever customizations I&#8217;d done. This way, you can automate the merging process and only have to go in if there are conflicts. That&#8217;s a big win to me. Then, if I actually do something with a plugin that others might find useful, I can offer up my own fork on GitHub, or submit it to the trunk if I think it&#8217;s useful enough to be included there.</p>
<p>Although Git was released in 2005 and GitHub in 2008, I included them on the 2009 list here because I think they have really broken through to the mainstream in a big way this past year. GitHub achieved meteoric rise during 2009. In January alone 17,000 new repositories were made, according to a talk given by GitHub founders at Yahoo in February of that year. In July of 2009 they had 90,000 unique repositories, double the previous year&#8211; and 45,000 forks of those repositories.</p>
<p>So, get on the bandwagon! Head over to GitHub and see what they have to offer. Or, if you don&#8217;t know where to start, check out this next useful resource for pointers &#8230;</p>
<h3><a href="http://www.ruby-toolbox.com/">The Ruby Toolbox</a></h3>
<p><a href="http://www.ruby-toolbox.com/"><img class="alignnone size-full wp-image-268" title="Toolbox_Red-256x256" src="http://www.thetruetribe.com/wp-content/uploads/2010/01/Toolbox_Red-256x256.png" alt="" width="256" height="256" /></a></p>
<p>The Ruby Toolbox is a wonderful resource for finding out what is popular. It uses metrics such as SVN commits and GitHub forks to determine which Ruby scripts are most popular. You can find out about a lot of great tools this way. I&#8217;ve discovered plenty of useful Rails gems and plugins here. There are also some useful standalone Ruby scripts for a variety of development tasks, such as Less, which doesn&#8217;t depend on Rails to do it&#8217;s thing.</p>
<h3><a href="http://github.com/sandal/prawn">Prawn</a>, PDF Generation Made Easy</h3>
<p>Prawn is a gem for generating PDFs. Let me tell you, working with PDFs is never easy, but Prawn greatly reduces the pain.</p>
<p>Check out <a href="http://railstips.org/2008/10/14/how-to-generate-pdfs-in-rails-with-prawn">this tutorial at RailsTips</a> for more info.</p>
<h3><a href="http://www.ruby-toolbox.com/categories/prototype_replacements.html">jRails</a></h3>
<p>I think it&#8217;s pretty obvious that jQuery has hit the big time in popularity. Endorsements by Microsoft, Amazon.com and other major players have led it to become the go-to JavaScript library of 2009. While Prototype still hangs in there, and MooTools has a great offering, an article I read recently summed it up perfectly when they said &#8216;jQuery is the guitar.&#8217; It had a screen grab of Google search results for guitar versus banjo, along with similar numbers for jquery versus mootools. You get the idea. If you aren&#8217;t using jQuery, you&#8217;re playing the banjo. If you want to really rock out, get on the bandwagon!</p>
<p>I am being facetious here but there is certainly some truth to the fact that a web developer in 2010 must be well-versed in jQuery. It&#8217;s also a viable alternative to Prototype in Ruby on Rails. In fact, I&#8217;ve heard that Rails 3 will be JavaScript framework agnostic, but don&#8217;t quote me on that.</p>
<p>In any case, you don&#8217;t have to wait until Rails 3 to start using jQuery in your Rails app. Simply install the jRails gem and you can go along using all those nifty Rails helpers, completely unaware that they are now implemented in jQuery instead of Prototype. Isn&#8217;t encapsulation great?</p>
<h3><a href="http://haml-lang.com">HAML</a></h3>
<p><a href="http://haml-lang.com"><img class="alignnone size-full wp-image-273" title="haml" src="http://www.thetruetribe.com/wp-content/uploads/2010/01/haml.gif" alt="" width="217" height="225" /></a></p>
<p>HAML (pronounced like Mark &#8220;Luke Skywalker&#8221; Hamill&#8217;s last name) is a great alternative to HTML. You write clean, concise HAML and the parser generates verbose and ugly HTML to serve up to the browser. Thus you can avoid typing those obnoxious closing tags that markup languages are so fond of. Keep your code simple, clean and pure. Or that&#8217;s the idea.</p>
<p>In practice, HAML can be a bit complex. Check out <a href="http://en.wikipedia.org/wiki/Haml">the HAML Wikipedia page</a> to see what I mean &#8212; look at all those obscure symbols. But once you learn what they all mean, it <em>is</em> a very concise, some might say beautiful language.</p>
<h3><a href="http://www.ruby-toolbox.com/categories/rails_file_uploads.html">Paperclip</a></h3>
<p>What can I say? Paperclip rocks. It is the standard for attachments in Rails and with good reason. It has been consistently updated, bug-fixed, and best of all, it is simple with not a bit of bloat. It requires the bare minimum of information from you, the developer, and does all the heavy lifting&#8211; even light lifting like database migrations&#8211; for you.</p>
<p>The next time you need to allow for file uploads in your Rails app, look no further than Paperclip.</p>
<h3><a href="http://github.com/mbleigh/acts-as-taggable-on">Acts_As_Taggable_On</a>, a Gem For Tagging</h3>
<p>Originally forked from Acts As Taggable On Steroids, the truncated form, has a number of improvements and goodies. Here is an excerpt from the Readme:</p>
<blockquote><p>This plugin was originally based on Acts as Taggable on Steroids by Jonathan Viney. It has evolved substantially since that point, but all credit goes to him for the initial tagging functionality that so many people have used.</p>
<p>For instance, in a social network, a user might have tags that are called skills, interests, sports, and more. There is no real way to differentiate between tags and so an implementation of this type is not possible with acts as taggable on steroids.</p>
<p>Enter Acts as Taggable On. Rather than tying functionality to a specific keyword (namely &#8220;tags&#8221;), acts as taggable on allows you to specify an arbitrary number of tag &#8220;contexts&#8221; that can be used locally or in combination in the same way steroids was used.</p></blockquote>
<p>Read more at <a href="http://github.com/mbleigh/acts-as-taggable-on">Github</a>.</p>
<h3><a href="http://ts.freelancing-gods.com/">Thinking Sphinx</a>, Front End to Sphinx Search Engine</h3>
<p><a href="http://ts.freelancing-gods.com/"><img class="alignnone size-medium wp-image-272" title="ts-logo" src="http://www.thetruetribe.com/wp-content/uploads/2010/01/ts-logo-300x64.gif" alt="" width="300" height="64" /></a></p>
<p>Thinking Sphinx is a great Ruby client to the Sphinx search engine that allows your Rails application to seamlessly integrate with Sphinx. This means you can get blazing-fast search results that are so fast because they&#8217;ve been optimized with filesystem-based indices, and even delta indices which only track changes to those indices, meaning they can avoid database calls when possible. Sounds fancy, huh? In practice, it&#8217;s a relatively painless set up that gets you professional quality search results. Sure, it can&#8217;t beat Google Mini, and feature for feature, heavy hitters like Java&#8217;s SOLR may win out, but for every project I&#8217;ve worked on, this has been sufficient. I like it a lot better than Ultrasphinx, the other Sphinx front end I&#8217;ve worked with.</p>
<p>All right, that&#8217;s all I have for now.  I&#8217;m sure I missed tons of great resources.</p>
<p>Please add your own favorite Ruby on Rails gems, plugins and resources in the comments!</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.thetruetribe.com%2F2010%2F01%2Fbest-of-2009-ruby-on-rails-edition%2F&amp;linkname=Best%20of%202009%2C%20Ruby%20on%20Rails%20Edition"><img src="http://www.thetruetribe.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.thetruetribe.com/2010/01/best-of-2009-ruby-on-rails-edition/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Random Integer Javascript snippet</title>
		<link>http://www.thetruetribe.com/2009/09/random-integer-javascript-snippet/</link>
		<comments>http://www.thetruetribe.com/2009/09/random-integer-javascript-snippet/#comments</comments>
		<pubDate>Sun, 06 Sep 2009 00:31:53 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.thetruetribe.com/?p=236</guid>
		<description><![CDATA[returns a random number between two digits passed in as arguments.

function randomInteger(low, high)
{
    return low + Math.floor(Math.random() * (high - low));
}

]]></description>
			<content:encoded><![CDATA[<p>returns a random number between two digits passed in as arguments.</p>
<pre class="js" name="code">
function randomInteger(low, high)
{
    return low + Math.floor(Math.random() * (high - low));
}
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.thetruetribe.com%2F2009%2F09%2Frandom-integer-javascript-snippet%2F&amp;linkname=Random%20Integer%20Javascript%20snippet"><img src="http://www.thetruetribe.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.thetruetribe.com/2009/09/random-integer-javascript-snippet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript Image Rotator Viewer</title>
		<link>http://www.thetruetribe.com/2008/06/javascript-image-rotator-viewer/</link>
		<comments>http://www.thetruetribe.com/2008/06/javascript-image-rotator-viewer/#comments</comments>
		<pubDate>Mon, 16 Jun 2008 06:01:00 +0000</pubDate>
		<dc:creator>grandecomplex</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://wordpress.thetruetribe.com/?p=42</guid>
		<description><![CDATA[Here is an image gallery written in JavaScript without the use of frameworks. It's an image rotator with functions to start and stop rotation, as well as actions when the user clicks a thumbnail.]]></description>
			<content:encoded><![CDATA[<p><a href="See a demo at http://www.alexgrande.com">See a demo at http://www.alexgrande.com</a></p>
<p>It is the images on the top right.</p>
<p>I wrote this in Object Oriented format so you can use it again and again on the same page.</p>
<p>Javascript:</p>
<pre class="js">var ImageGallery = new Function();

ImageGallery.prototype = {
 initialize: function(mainImage, listWrapper){
  // large image that is shown
  this.mainImage = document.getElementById(mainImage);
  // a list of all the anchors for the thumbnails. Must be a tags for graceful degradation
  this.thumbnails = document.getElementById(listWrapper).getElementsByTagName("a");
  // 0 image is shown already so the first one we want to switch to is the next image or 1
  this.i = 1;
  // this is a work around to allow calling this within nested functions
  var Scope = this;
  // Here starts the rotating of the image by first focusing the thumbnail, then switch the primary image
  this.start = setInterval(function(){
   Scope.focusCall();
  // Here we choose 5 seconds in between each image change. You may want to change this.
  }, 5000);
  // This lets the browser know to do something if one of the thumbnails is clicked
  this.clickEvent();
 },

 // This stops the rotation of the thumbnails. We do that if the user clicks one of them
 stop: function(){
  if (this.start)
   clearInterval(this.start);
 },

 // When an thumbnail loses focus we must use this css class now
 resetBorderColor: function(reset){
  reset.getElementsByTagName("img")[0].className="thumbnailDefault";
 },

 // When the thumbnail gains focus we most give it the corresponding styles
 focusBorderColor: function(focused){
  focused.getElementsByTagName("img")[0].className="thumbnailFocus";
 },

 // Here we grab the href of the a tags and make their path be the path of the current image
 imageRotator: function(){
  this.mainImage.src = this.thumbnails[this.i].href;
  this.previousImage = this.thumbnails[this.i];
  this.i++;
  // This closes the loop for the rotation
  if (this.i == this.thumbnails.length)
   this.i = 0;
 },

 // We focus the thumbnail
 focusCall: function(){
  // reset the last image that was shown
  if (typeof this.previousImage != 'undefined')
   this.resetBorderColor(this.previousImage);
  // Remember the newer one
  this.currentImage = this.thumbnails[this.i];
  // Give the newer image some focus
  this.focusBorderColor(this.currentImage);
  var Scope = this;
  // Les that have image rotate to the new one 300 miliseconds after the thumbnails get the css focus
  window.setTimeout(function(){
   Scope.imageRotator()
  // You may want to change this number
  }, 300);

 },

 // This is what happens when you click the thumbnails
 clickEvent: function(){
  var Scope = this;
  for (k = 0; k &lt; this.thumbnails.length; k++) {
   this.thumbnails[k].onclick = function(){
    if (typeof Scope.previousImage != 'undefined')
     Scope.resetBorderColor(Scope.previousImage);
    Scope.focusBorderColor(this);
    // Stop the rotation
    Scope.stop();
    // This is where the switching happens for the click
    Scope.mainImage.src = this.href;
    Scope.previousImage = this;
    // Make sure to not allow default behavior of the a tag
    return false;
   }
  }
 }

}</pre>
<p>This is to load it on the window object and create an instance of the viewer</p>
<pre class="js">var imageGallery1 = new ImageGallery();

// Not sure where I got this.. I didn't write this but it allows you to load multiple functions on the window.onload.
function addLoadEvent(func) {
 var oldonload = window.onload;
 if (typeof window.onload != "function") {
  window.onload = func;
 } else {
  window.onload = function() {
   oldonload();
   func();
  }
 }
}

var onLoad = function() {
 imageGallery1.initialize("index_largepic_display", "index_thumbnail_display");
}

addLoadEvent(onLoad);</pre>
<p>For the version on my homepage alexgrande.com here is the CSS and HTML. The CSS is up to you but I suggest following a similar mode with the HTML</p>
<p>HTML:</p>
<pre class="html">&lt;div id="gallery"&gt;
     &lt;ul id="index_thumbnail_display"&gt;
        &lt;li&gt;
   &lt;a href="images/index/fernlarge.jpg" &gt;
  &lt;img class="thumbnailDefault" src="images/index/fernthumb.jpg" alt="A picture of a fern just as it is unraveling in front of a log." /&gt;
   &lt;/a&gt;
 &lt;/li&gt;

        &lt;li&gt;
   &lt;a id="partythumb" href="images/index/partylarge.jpg" &gt;
      &lt;img class="thumbnailDefault" src="images/index/partythumb.jpg" alt="Downtown Seattle at night." /&gt;
   &lt;/a&gt;
 &lt;/li&gt;

        &lt;li&gt;
   &lt;a id="alexthumb" href="images/index/alexlarge.jpg" &gt;
      &lt;img class="thumbnailDefault" src="images/index/alexthumb.jpg" alt="I'm on a laptop at night in a field on using the internet via hacking a telephone box...legally." /&gt;
   &lt;/a&gt;
 &lt;/li&gt;
        &lt;li&gt;
   &lt;a href="images/index/trucks.jpg" &gt;
     &lt;img class="thumbnailDefault" alt="Trucks lined up in Sodo in Seattle at night." src="images/index/trucksthumb.jpg" /&gt;
   &lt;/a&gt;
        &lt;/li&gt;
      &lt;/ul&gt;
      &lt;img id="index_largepic_display" src="images/index/fernlarge.jpg" alt="A picture of a fern just as it is unraveling in front of a log." /&gt;
&lt;/div&gt;</pre>
<p>CSS:</p>
<pre class="css">div#gallery {
 position:relative;
 float: left;
 overflow: hidden;
 width: 65%;
}

img#index_image_display {
 border:1px black solid;
 margin-bottom:20px;
}

ul#index_thumbnail_display {
 list-style-type:none;
 position:absolute;
 top: 0;
 left: 0;
 margin-top: 15px;
}

ul#index_thumbnail_display li a {
 padding:10px;
}

.thumbnailDefault {border: 1px solid gray !important;}

.thumbnailFocus {border: 1px solid red !important;}</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.thetruetribe.com%2F2008%2F06%2Fjavascript-image-rotator-viewer%2F&amp;linkname=JavaScript%20Image%20Rotator%20Viewer"><img src="http://www.thetruetribe.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.thetruetribe.com/2008/06/javascript-image-rotator-viewer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Saving State: What To Do When Users Leave</title>
		<link>http://www.thetruetribe.com/2008/06/saving-state-what-to-do-when-users-leave/</link>
		<comments>http://www.thetruetribe.com/2008/06/saving-state-what-to-do-when-users-leave/#comments</comments>
		<pubDate>Fri, 13 Jun 2008 06:10:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[JSON]]></category>

		<guid isPermaLink="false">http://wordpress.thetruetribe.com/?p=41</guid>
		<description><![CDATA[In this era of rich JavaScript applications, so much
focus is given to the features of the application that one
crucial element is often overlooked: What happens when the
user leaves the page? We take it for granted that pages
will look the same when we leave and return, but a new
question merges for sites using rich JavaScript
interaction: If [...]]]></description>
			<content:encoded><![CDATA[<p>In this era of rich JavaScript applications, so much<br />
focus is given to the features of the application that one<br />
crucial element is often overlooked: What happens when the<br />
user leaves the page? We take it for granted that pages<br />
will look the same when we leave and return, but a new<br />
question merges for sites using rich JavaScript<br />
interaction: If the user leaves and returns to the page,<br />
will the application state be preserved?<span id="more-41"></span></p>
<p>The effects of losing application state can range from<br />
minor annoyances like losing what page you&#8217;re on, to<br />
all-out frustration after losing a carefully-typed message<br />
because you accidentally triggered the browser&#8217;s back<br />
button. (It&#8217;s easier than you think&#8211; hitting backspace<br />
when the document is in focus triggers the back button in<br />
most browsers). Couple this with the fact that some users<br />
may expect pages to save form data, because of their prior<br />
experience to that effect, and it becomes apparent that a<br />
robust strategy for preserving application state must be<br />
devised.</p>
<p>Browsers automatically save data entered into form<br />
fields, but all JavaScript variables are lost when the user<br />
leaves the page. Furthermore, any form fields that were<br />
created by JavaScript will also be lost. So, for all but<br />
the most simple applications, JavaScript must have a<br />
strategy for saving state that deals with these<br />
limitations.</p>
<p>Some sites like <a href="&lt;br"></a> &#8220;http://www.thesixtyone.com&#8221;&gt;<em>thesixtyone.com</em><br />
reside entirely on a single page and capture users&#8217; back<br />
button clicks with named anchors. But, try writing a wall<br />
post on Facebook and you&#8217;ll find that it does not save the<br />
post if you leave the page. Accidentally pressing backspace<br />
is all too easy in cases like this where typing is<br />
involved, which is why sites like Gmail and Blogger warn<br />
users that they will lose data before leaving the page.</p>
<h3>How To Warn Users Before Leaving the Page</h3>
<p>One way you can do this is by assigning a confirmation<br />
message to the return value of the<br />
<em>window.onbeforeunload</em> event handler. The user will<br />
be presented with two choices, <em>OK</em> and<br />
<em>Cancel</em>, along with a custom message of your<br />
choosing.</p>
<p>In the following example, we regsiter an anonymous<br />
function as the event handler for<br />
<em>window.onbeforeunload</em>, and add our own custom<br />
message:</p>
<h5>Using <em>window.onbeforeunload</em> to confirm if a<br />
user wants to leave the page (<a href="&lt;br"></a> &#8220;/examples/saving-state/example-1.html&#8221;&gt;example 1)</h5>
<pre class="js:nocontrols">window.onbeforeunload = function() {
  return "You will lose any unsaved information.";
};</pre>
<p>The browser displays your custom message, given in the<br />
return statement of the <em>onbeforeunload</em> event<br />
handler, along with the browser default message. In<br />
Firefox, the result is:</p>
<blockquote><p>Are you sure you want to navigate away from this<br />
page?<br />
You will lose any unsaved information.<br />
Press OK to continue, or Cancel to stay on the current<br />
page.</p></blockquote>
<h3>Retaining Data When Users Do Leave the Page</h3>
<p>You may opt to silently save the user&#8217;s data when they<br />
leave the page. This may give a better user experience<br />
since they are not confronted with a choice, and their data<br />
is saved automatically.</p>
<p>This is one of the times where Ajax comes in handy.<br />
However, there are also other ways to do this without using<br />
Ajax, such as cleverly storing information in named anchors<br />
or hidden form fields. We&#8217;ll examine each of these<br />
practices in more depth, but suffice it to say that the<br />
hidden form fields approach works better for conventional<br />
websites that are spread across many pages, whereas storing<br />
data in named anchors is better for single-page, pure<br />
JavaScript applications.</p>
<p>It turns out that while you could (and should) save<br />
state to the server using Ajax, for some cases you will<br />
want to avoid Ajax altogether and use a simpler,<br />
clientside-only model.</p>
<h3>Using Hidden Form Fields to Save State</h3>
<p>As mentioned, all JavaScript objects are lost when the<br />
user leaves or refreshes the page. But, browsers will<br />
retain data in form fields, provided that the form elements<br />
were not generated using JavaScript. Given this limitation,<br />
it is necessary to save JavaScript variables (or the<br />
serialized JSON strings of such objects) to hidden form<br />
fields if they need to be retained.</p>
<p>Here is a basic example showing how variables can be<br />
stored to hidden form fields and restored on page load:</p>
<pre class="html:nocontrols">
<input id="saved-data" type="hidden" /></pre>
<h5>Saving data in hidden form fields (<a href="&lt;br"></a> &#8220;/examples/saving-state/example-2.html&#8221;&gt;example 2)</h5>
<pre class="js:nocontrols">// The variable userData is some necessary information we need from the user.
// The first time the user visits the page, they must enter this data manually.
// But, when leaving and returning to the page (or refreshing the page), we'll check
// if they already entered the data, and if so, restore it from a hidden form field.

var userData;

// Register event handlers
window.onload = function() {
 restoreState();
 if (!userData) {
    userData = prompt('Please enter the data to save', 'test');
 }
 document.write("userData: " + userData);
}

window.onbeforeunload = saveState;

// This function is called onbeforeunload and writes the userData to the hidden form field
function saveState() {
   document.getElementById('saved-data').value = userData;
}

// This function is called onload and checks if any data is present in the hidden form field
// If so, it defines userData to be the saved data
function restoreState() {
   var savedData = document.getElementById('saved-data').value;
   if (savedData != "") {
        userData = savedData;
   }
}</pre>
<p>In the above example, all we&#8217;re saving is one string<br />
from the user. But what about cases where we need to save<br />
many different values? For instance, what if we&#8217;re using<br />
object-oriented code and have numerous nested objects<br />
within objects we need to store? At times like this,<br />
<strong>serializing objects with JSON</strong> is the<br />
easiest way to store the data. Without using JSON, you&#8217;d<br />
have to create a hidden form field for each value you want<br />
to save, whereas JSON can create string representations of<br />
complex data structures that you can easily <em>eval</em><br />
back into JavaScript objects once they&#8217;re fetched from the<br />
DOM.</p>
<h3>So What is JSON, Anyway?</h3>
<p>JSON (pronounced &#8220;Jason&#8221;), short for <em>JavaScript<br />
Object Notation</em> is a lightweight, human- and<br />
machine-readable way to represent the string serializations<br />
of objects. These strings can be evaluated back into<br />
JavaScript objects as needed. For instance, say I create a<br />
JavaScript object to represent a person (in this case,<br />
me):</p>
<pre class="js:nocontrols">var person = new Object();
person.name = "Jonah";
person.age = 24;
person.gender = "male";
person.location = "Seattle, WA";</pre>
<p>The JSON representation of this object is as<br />
follows:</p>
<pre class="js:nocontrols">{
    'person': {
        'name': 'Jonah',
        'age': 24,
        'gender': 'male',
        'location': 'Seattle, WA'
    }
}</pre>
<p>Then, if you need to reconstruct the object at a later<br />
point, you can simply eval the JSON string:</p>
<pre class="js:nocontrols">var jsonString = "{'person': {'name': 'Jonah', 'age': 24, 'gender': 'male', 'location': 'Seattle, WA'}}";
var person = eval( '(' + jsonString + ')' );    

console.assert(person.name == 'Jonah');
console.assert(person.age == 24);
console.assert(person.gender == 'male');
console.assert(person.location == 'Seattle, WA');</pre>
<p>If you&#8217;ve written JavaScript using object literal syntax<br />
before, this should be familiar to you. The only minor<br />
difference between JSON and the standard JavaScript object<br />
literal syntax is that JSON requires quotes around key in a<br />
key/value pair. So, <em>name</em> is a valid JavaScript key<br />
but in JSON it would have to be <em>&#8216;name&#8217;</em>. (Note: It<br />
doesn&#8217;t matter if you use single- or double-quotes, as long<br />
as they are matched).</p>
<h3>Stringifying Objects in JSON</h3>
<p>To use JSON, it&#8217;s necessary to include a library of JSON<br />
methods. Don&#8217;t worry, the library is quite small. The<br />
entire thing shouldn&#8217;t be more than 2k and can be obtained<br />
from <a href="http://www.json.org/js.html">json.org</a>.<br />
Eventually, the JSON methods will be included as part of<br />
the core JavaScript language, but for the time being, we&#8217;re<br />
left to use the methods provided by json.org or those found<br />
in libraries such as MooTools, Prototype and jQuery.</p>
<p>Depending on the library used, the method names for<br />
serializing an object into a JSON string are different.<br />
But, they are all used in rather similar fashion. For now,<br />
we&#8217;ll assume you&#8217;re using the library from <a href="&lt;br"></a> &#8220;http://www.json.org/js.html&#8221;&gt;json.org and use the<br />
method names provided in its API.</p>
<h5>Saving complex JavaScript data structures as JSON<br />
strings (<a href="/examples/saving-state/example-3.html">example 3</a>)</h5>
<pre class="js">// The variable userData is some necessary information we need from the user.
// The first time the user visits the page, they must enter this data manually.
// But, when leaving and returning to the page (or refreshing the page), we'll check
// if they already entered the data, and if so, restore it from a hidden form field.

var userData;

// Register event handlers
window.onload = function() {
 restoreState();
 if (!userData) {
    userData = new Object();
    userData.name = prompt('Please enter a name', 'Jonah');
    userData.age = parseInt(prompt('Please enter an age', '24'));
    userData.gender = prompt('Please enter a gender', 'male');
    userData.location = prompt('Please enter a location', 'Seattle, WA');
 }
 displayData(userData);
}

window.onbeforeunload = saveState;

// This function is called onbeforeunload and writes the userData to the hidden form field
function saveState() {
   document.getElementById('saved-data').value = JSON.stringify(userData);
}

// This function is called onload and checks if any data is present in the hidden form field
// If so, it defines userData to be the saved data
function restoreState() {
   var savedData = document.getElementById('saved-data').value;
   if (savedData != "") {
        userData = eval( '(' + savedData + ')' );
   }
}

// This is a helper function that iterates through each property in an object and renders it in HTML.
function displayData(obj) {
 var list = document.createElement('ul');
 for (var property in obj) {
    var text = document.createTextNode(property + ': ' + obj[property])
     var line = document.createElement('li');
     line.appendChild(text);
     list.appendChild(line);
 }
 document.getElementsByTagName('body')[0].appendChild(list);
}</pre>
<p>This example is pretty similar to the previous one where<br />
we saved a string. The only difference is that in this<br />
case, the string is a representation of a complex<br />
JavaScript object. In fact, you can save the entire state<br />
of your application in one JSON string, as long as the<br />
application state is completely stored as properties of a<br />
single object. There are a few minor gotchas, such as<br />
having to add parentheses around the JSON string when<br />
evaluating it. But, overall this is a clean and<br />
straightforward approach that is very useful when complex<br />
data structures must be retained.</p>
<h3>Using Named Anchors to Save State</h3>
<p>An alternate option for retaining state is to not<br />
actually let the user leave the page at all. Rather, when<br />
following links on the site, update the named anchor<br />
(everything after the number sign in a URL), instead of<br />
changing the actual document being displayed.</p>
<p>The problem that this is trying to solve is the fact<br />
that Ajax applications will normally break the back button.<br />
A user loads the application on the homepage and clicks to<br />
visit a different page, but since the new page is loaded in<br />
via Ajax, the browser URL doesn&#8217;t change. Then the user<br />
clicks the back button and leaves the application<br />
altogether&#8211; not the intention of the user, who just wanted<br />
to get back to the homepage.</p>
<p>Storing data in named anchors offers a solution to this<br />
problem. Each time the application state changes,<br />
JavaScript updates the named anchor with a token<br />
representing the application state. When the page is<br />
loaded, data is read from the named anchors and the state<br />
can be restored.</p>
<p>Say you&#8217;re on the homepage of an ecommerce Ajax<br />
application and click on a product you&#8217;d like to view.<br />
Instead of changing URLs to the detail page, the<br />
application loads in new data with Ajax. So, when a user<br />
clicks on the new Brad Mehldau CD for instance, instead of<br />
going to a different URL (yoursite.com/brad-mehldau/) the<br />
document URL remains the same, but JavaScript updates the<br />
named anchor: yoursite.com/#brad-mehldau.</p>
<p>One site which does this unbelievably well is <a href="&lt;br"></a> &#8220;http://www.thesixtyone.com&#8221;&gt;<em>thesixtyone.com</em><br />
(Thanks, Derek!). The entire site resides in one document,<br />
truly a rich JavaScript application if I&#8217;ve ever seen one.<br />
But, despite the fact that the entire application is<br />
contained in a single document URL, due to clever use of<br />
named anchors, the site has full back button support and<br />
you can even email working links to friends.</p>
<p>Implementing code to save state in named anchors is out<br />
of scope for this article, but you can see how it is<br />
somewhat similar to saving data in hidden form fields. In<br />
this case, there are a few more issues to mitigate and it&#8217;s<br />
somewhat tricky, but the reward is an Ajax site with fully<br />
functional back button support and the ability to share<br />
links &#8212; worth all the effort, in my book.</p>
<h3>So What Use is Ajax, Then?</h3>
<p>Since we&#8217;ve made it this far, you might think that there<br />
is no use for Ajax in all this. Actually, Ajax is great for<br />
saving state to the server, especially for saving data<br />
beyond the lifespan of the browser session. Ajax can be<br />
used to save messages periodically (like how Gmail and<br />
Google Docs automatically save on a timer every few<br />
minutes). It can also be used to send data when the user<br />
leaves the page by capturing the <em>onbeforeunload</em><br />
event, but this is unreliable and I would not depend on<br />
this Ajax request to complete. Instead, try to save the<br />
data before the user attempts to leave the page, by either<br />
firing the Ajax request on a timer or another event on the<br />
page (leaving focus on a form element, for example).</p>
<p>Some frameworks like Prototype have serialize() methods<br />
that return URL query string representations of objects.<br />
This is perfect for saving data through GET requests. Yes,<br />
GET requests have a 2000-character limit and other<br />
limitations, but in most cases this won&#8217;t be an issue. Even<br />
without helper methods to serialize objects, it&#8217;s a fairly<br />
simple matter to construct an Ajax request that will save<br />
the necessary data to the server.</p>
<h3>Wrapping Up</h3>
<p>To re-cap, it is a good practice to check if users are<br />
sure they want to leave a page when they are entering<br />
information, but it&#8217;s even better to silently save that<br />
information for them. (Arguably you would want to do both,<br />
like how Gmail and Blogger save state <em>and</em> ask<br />
users if they are sure they want to leave the page). There<br />
are many different ways to save state, some purely<br />
client-side and others relying on saving data to the server<br />
with Ajax. The solutions which save data to the server are<br />
suitable for times when the data needs to be saved beyond<br />
the browsing session.</p>
<p>Of the two client-side solutions explored, hidden form<br />
fields and named anchors, the former is more suitable for<br />
conventional websites spanning many pages while the latter<br />
better suits single-page Ajax applications. Using named<br />
anchors also has the added benefit of allowing users to<br />
bookmark and send links to the JavaScript application in<br />
various states, and the state is preserved beyond the<br />
browsing session.</p>
<p>Whatever strategy you follow, your users will thank you<br />
for the time saved and frustration avoided of having to<br />
re-enter lost information.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.thetruetribe.com%2F2008%2F06%2Fsaving-state-what-to-do-when-users-leave%2F&amp;linkname=Saving%20State%3A%20What%20To%20Do%20When%20Users%20Leave"><img src="http://www.thetruetribe.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.thetruetribe.com/2008/06/saving-state-what-to-do-when-users-leave/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>AJAX Google API to Minify Javascript using Ruby on Rails</title>
		<link>http://www.thetruetribe.com/2008/06/ajax-google-api-to-minify-javascript-using-ruby-on-rails/</link>
		<comments>http://www.thetruetribe.com/2008/06/ajax-google-api-to-minify-javascript-using-ruby-on-rails/#comments</comments>
		<pubDate>Sun, 08 Jun 2008 05:36:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://wordpress.thetruetribe.com/?p=38</guid>
		<description><![CDATA[How to optimizing JavaScript performance in Ruby on Rails. This will only focus on one aspect of JS performance optimization, namely, writing a build script to concatenate/minify the JS, and setting up Rails to easily toggle between the compressed and normal files. Also, if your site uses a JavaScript library, we&#8217;ll explore including it from [...]]]></description>
			<content:encoded><![CDATA[<p>How to <span style="font-weight: bold;">optimizing JavaScript performance</span> in Ruby on Rails. This will only focus on one aspect of JS performance optimization, namely, writing a build script to concatenate/minify the JS, and setting up Rails to easily toggle between the compressed and normal files. Also, if your site uses a JavaScript library, we&#8217;ll explore including it from Google&#8217;s <a href="http://code.google.com/apis/ajaxlibs/">AJAX Libraries API</a>.<span id="more-38"></span></p>
<p>The reason to do these optimizations are for client-side performance. Concatenating many files together into one is especially effective: 10 1-kilobyte files are much slower to download than a single 10k file. You might not think it makes much of a difference, but I estimate that removing 10 additional JS files, for instance, will shave 500-1000ms off latency. Plus, all of the time spent loading the JS will leave the page blank, if you put it in the head.</p>
<p>We&#8217;ll need to be able to easily toggle between fully commented code and minified code, both for code hosted by us and code from the Google AJAX Libraries API. Since Google offers both minified and normal versions of the code, this should be no problem.</p>
<h3>Including JavaScript in Ruby on Rails</h3>
<p>First of all, let&#8217;s look at how JavaScript is included in Ruby on Rails, the <span style="font-family:Courier New;">javascript_include_tag</span> method. The method quite simply takes any number of source URLs and returns an HTML script tag for each of the sources provided. For instance:</p>
<pre class="code">  javascript_include_tag("script1.js", "script2.js", "script3.js")</pre>
<p><strong>Result:</strong></p>
<p style="font-family: Courier,monospace;">&lt;script type=&#8221;text/javascript&#8221; src=&#8221;/javascripts/script1.js&#8221;&gt;&lt;/script&gt;</p>
<p>&lt;script type=&#8221;text/javascript&#8221; src=&#8221;/javascripts/script2.js&#8221;&gt;&lt;/script&gt;</p>
<p>&lt;script type=&#8221;text/javascript&#8221; src=&#8221;/javascripts/script3.js&#8221;&gt;&lt;/script&gt;</p>
<p>There&#8217;s a little bit of magic you can do which is to include all JavaScript files in the /public/javascripts folder automatically, as well as having them concatenated into a single file. It looks like this:</p>
<pre class="code">  javascript_include_tag :all, :cache =&gt; true # when ActionController::Base.perform_caching is true</pre>
<p>The resulting code is:</p>
<p style="font-family: Courier,monospace;">&lt;script type=&#8221;text/javascript&#8221; src=&#8221;/javascripts/all.js&#8221;&gt;&lt;/script&gt;</p>
<p>If you don&#8217;t want them concatenated into a single file, e.g. for development purposes, you could do something like this:</p>
<pre class="code"># config/environments.rb:
DEBUG_JS = false;

# environments/development.rb:
DEBUG_JS = true;

# app/views/layouts/site.html.erb or wherever you include the JavaScript in your site:</pre>
<p>I&#8217;m not sure how to integrate JSMin, YUICompressor or any other minification into the cached file, though, so I will explore the options for manual building and inclusion next.</p>
<p>Something else to remember is that caching needs ActionController::Base.perform_caching to be true in order to work. This is the default in production, but not development, though of course you can override it in your <span style="font-family:Courier New;">environments/development.rb file.</span> For more information, view the <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html#M001024">docs for the javascript_include_tag</a>.</p>
<h3>JavaScript Concatenation and Minification</h3>
<p>Next, we&#8217;ll write a custom build script to generate a concatenated, minified version of our files. Ideally, Rails would automatically run it through a minifier, but I&#8217;m not sure how to set that up. In the meantime, this is a working solution that is pretty straightforward and requires minimal effort. I wish I were more skilled at shell scripting (and I highly urge readers to contribute their own code), but I&#8217;ll show my implementation as an example regardless.</p>
<p>I&#8217;m on a Windows machine and wrote it as a batch file (.bat), but you can easily do this on linux, just using pipe (the | character) instead of the two right-angle brackets (&gt;&gt;). Here goes:</p>
<pre>java -jar yuicompressor-2.3.5.jar "script1.js" -o main.js
java -jar yuicompressor-2.3.5.jar "script2.js" &gt;&gt; main.js
java -jar yuicompressor-2.3.5.jar "script3.js" &gt;&gt; main.js
java -jar yuicompressor-2.3.5.jar "script4.js" &gt;&gt; main.js</pre>
<p>Nothing too sophisticated, just a straightforward script that generates main.js using the YUICompressor. To use it, simply run the batch file in the same folder as the JavaScripts and yuicompressor-2.3.5.jar. It will output a main.js file. I chose to run it separately for each individual file so if there are any errors, you can see where they occurred. If you concatenate all of the files into one and then compress it, debugging is difficult as the line number which threw the error is unknown.</p>
<p>I chose to use YUICompressor over JSMin since it seems to have better error messaging, warnings, and be a bit more strict. One of my former colleagues did some tests that determined that JSMin was faster in terms of using less CPU than YUICompressor (and certainly for minifiers which use eval(), such as Dean Edwards&#8217; packer). Unfortunately, I can&#8217;t remember the specifics of the test or which platforms it was on, so that data is pretty much worthless. In any case, I decided on YUICompressor but you can use JSMin or whichever minifier you prefer.</p>
<p>If you are going to use YUICompressor, <strong>you must have Java installed</strong> and included in your path. If it isn&#8217;t in your path, you can use the full path to Java, for instance, <span style="font-family:Courier New;">&#8220;C:\Program Files\Java\bin\java.exe&#8221; -jar [filename] [options].</span></p>
<h3><span style="font-family:Courier New;">Using the Google AJAX Libraries</span></h3>
<p><span style="font-family:Courier New;"><br />
<a href="http://code.google.com/apis/ajaxlibs/" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}"><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer;" src="http://www.thetruetribe.com/uploaded_images/google-ajax-api-735798.png" border="0" alt="" /></a><br />
</span></p>
<p>Depending on your opinion about Google&#8217;s recent offer to host the world&#8217;s JavaScript frameworks with its <a href="http://code.google.com/apis/ajaxlibs/">AJAX Libraries API</a>, you may not find this suggestion too useful, but I think it&#8217;s helpful, especially to those without access to their hosting provider&#8217;s response header settings, to present here. Without going into too much detail, suffice it to say that besides the caching benefit of using Google&#8217;s API, their servers are configured &#8220;correctly&#8221; for best performance (far future expires headers, Gzip, etc).</p>
<p>One thing, though, is that you will want to include a minified version of the JavaScript in production and a full version in development, to ease debugging. It&#8217;s impossible to debug minified JavaScript (don&#8217;t even try), so we have to set a toggle like in the above example. Say your site is including jQuery. You may want to include a minified version on the live server but read the full code locally.</p>
<h3>Toggling Minified Google JS</h3>
<p>Here&#8217;s how you can include minified jQuery in the production Ruby on Rails code while including the full jQuery library, comments and all, in development:</p>
<p>&lt;</p>
<p>Or, if you didn&#8217;t want to include everything in the JS folder, and wanted to granularly include only specific files, you might rewrite it like so:</p>
<p>That&#8217;s all there is to it! Just switch the DEBUG_JS flag when you want to test in development mode with/without compression, and don&#8217;t worry about when it&#8217;s in production since it will always serve up the minified, concatenated JavaScript. The logic ensures that you won&#8217;t accidentally start serving up the separate files in production, while giving you the flexibility to store your JavaScript in as many files as you like without negative consequences on the front end, as well as reading fully-commented code./p&gt;</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.thetruetribe.com%2F2008%2F06%2Fajax-google-api-to-minify-javascript-using-ruby-on-rails%2F&amp;linkname=AJAX%20Google%20API%20to%20Minify%20Javascript%20using%20Ruby%20on%20Rails"><img src="http://www.thetruetribe.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.thetruetribe.com/2008/06/ajax-google-api-to-minify-javascript-using-ruby-on-rails/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Conducting Technical Interviews for Web Developers</title>
		<link>http://www.thetruetribe.com/2008/05/conducting-technical-interviews-for-web-developers/</link>
		<comments>http://www.thetruetribe.com/2008/05/conducting-technical-interviews-for-web-developers/#comments</comments>
		<pubDate>Sun, 25 May 2008 21:41:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://wordpress.thetruetribe.com/?p=32</guid>
		<description><![CDATA[Presumably most readers of this blog will have been through a technical interview, and I&#8217;m betting that some of them have to give technical interviews as well. The purpose of this article is to go over some of the points to consider while conducting the interview, as well as suggestions for coming up with good [...]]]></description>
			<content:encoded><![CDATA[<p>Presumably most readers of this blog will have been through a technical interview, and I&#8217;m betting that some of them have to give technical interviews as well. The purpose of this article is to go over some of the points to consider while conducting the interview, as well as suggestions for coming up with good questions to ask.<span id="more-32"></span></p>
<p>The first thing to understand as an interviewer is the requirements of the job position and what competencies a candidate must possess to be a good fit. If the job is for back-end development, then experience working with databases, performance tuning, and writing scalable code is crucial, and only a cursory understanding of HTML and CSS is required. Alternately, for UI development work, it isn&#8217;t necessary to have a candidate who is wrapped up in the back-end code or has Big O notation at the tip of their tongue. There are certainly jacks-of-all-trades but when interviewing, it&#8217;s better to <span style="font-weight: bold;">focus on a few crucial areas</span> than try to set high standards for all areas across the board.</p>
<p>These are some of the areas you may want to explore, depending on the requirements of the position:</p>
<h3>Software Development Skills</h3>
<ul>
<li>Proficiency in at least one high-level programming language: C++, Java</li>
<li>Basic understanding of object-oriented design &amp; analysis: classes/inheritance, interface vs implementation, encapsulation</li>
<li>Experience with source code version control: SVN, CVS, P4</li>
<li>Algorithms: binary search, quicksort</li>
<li>Data structures: array, hash, linked list</li>
<li>Complexity/performance analysis: Big O notation, performance testing</li>
</ul>
<h3>Web Development Skills</h3>
<ul>
<li>Candidate tests web-deployed code in big 3 browsers: IE6+, Firefox 2+, Safari 2+</li>
<li>Candidate uses browser-specific debugging tools: IE Web Developer Toolbar, Script Debugger/Script Editor (IE), Firebug (Firefox), WebKit/Drosera (Safari)</li>
<li>Extensive knowledge of at least one JS framework: jQuery, Prototype, MooTools, YUI</li>
<li>Experience creating dynamic, database-driven websites: PHP/JSP/ASP, MySQL etc</li>
<li>Candidate uses Selenium for front-end automated testing</li>
<li>Proficient in Fireworks or other image editing software, and knowledgeable about how to best export images for the web (CSS sprites, GIF/JPG/PNG, etc)</li>
<li>Follows front-end best practices like CSS-based layouts and unobtrusive JavaScript</li>
<li>Experience developing rich user interfaces (drag-and-drop, Ajax, web applications/RIAs, animation effects)</li>
</ul>
<h3>General and Miscellaneous Skills</h3>
<ul>
<li>Familiarity with agile development methodology: scrum, burndown charts</li>
<li>Proficiency at Search Engine Optimization (SEO), Search Engine Marketing (SEM), and related fields</li>
<li>Knowledgeable about security vulnerabilities in code. Experience with threat analysis software (e.g. Fortify for Java)</li>
<li>Familiarity with automated unit/integration tests: JUnit (Java), Selenium (front end)</li>
<li>DBA-related skills such as database optimization</li>
<li>Usability skills and knowledge of user behavior</li>
<li>Project management skills</li>
</ul>
<p>You can choose from these or other criteria to create a baseline for what makes an ideal candidate, ignoring the skills which aren&#8217;t relevant. Once you&#8217;ve determined the skills necessary for the position, you may find that a Ph.D. is less qualified than someone without a college degree, depending on the skills required. So, never make assumptions about candidates simply based on their credentials or previous work experience. Developers can take drastically different amounts of time to complete tasks based on their prior experience and their ability to learn new things quickly.</p>
<h3>Criteria for Various Job Positions</h3>
<p>Let&#8217;s look at a few example job positions and apply criteria from the list above.</p>
<h4>Quality Assurance Engineer</h4>
<p>An ideal QA engineer for a website will be an expert at creating automated test suites for front and back end, and should also be aware of security issues. So you could focus the interview on how they choose to write test suites, and come up with sample test suites for real-life objects (e.g. an elevator). Then you could ask them to list some of the common security threats (e.g. <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">XSS</a>, <a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery">XSRF</a>) and how to mitigate them.</p>
<p>Of course, if you already have a security engineer at your company, then you may not require your QA to wear another hat. But for most small- to medium-sized businesses, it&#8217;s most efficient and cost effective for your developers to wear many hats. In fact, you may have a software developer who also does QA on the site, or a QA engineer who does project management. It all depends on the size of your company and the particular restraints in budget for your development team.</p>
<h4>Software Developer / Programmer</h4>
<p>Let me say right off the bat that I&#8217;ve never conducted a software development interview. But, I have been through a few, and I have an idea of what types of questions I would ask depending on the position.</p>
<p>There are some general software development skills that I would consider, such as experience with SVN (or other source control), automated testing, knowledge of data structures and algorithms, and perhaps object oriented design and analysis.</p>
<p>If the candidate is a Java developer, then you can ask about things like exception handling, reflection, familiarity with libraries (Swing, Struts, JSF etc), or other Java-specific questions. If they are a C++ developer then you should drill down into memory management, constructors/destructors, and other tropes of C++. It&#8217;s up to you as the interviewer to determine the right questions to ask based on the job requirements, or to find someone else to conduct the interview if you can&#8217;t. I know I would have a hard time conducting an interview with a C++ developer, unless I had a &#8220;cheatsheet&#8221; with all the correct answers to the questions.</p>
<h4>Web Developer</h4>
<p>For a web development position, the focus will be less on knowledge of traditional computer science and more on the candidate&#8217;s knowledge of current best practices. Since best practices are always changing, the ideal web developer is enthusiastic and passionate about their field, and stays up to date by reading/contributing to blogs, belonging to email lists or other online communities and generally <span style="font-weight: bold;">keeping &#8220;in the know&#8221; about the best way to solve problems</span>.</p>
<p>Unlike traditional computer programming, in which code is executed in a controlled environment and changes to the language take years to complete, web development is a fast-paced field where changes happen all the time and code is executed in a wide range of environments, each with its own caveats and bugs. So, the ideal web developer is familiar with the issues surrounding development on each platform and environment, especially the Big 3 browsers (IE, Firefox and Safari).</p>
<h3>Interview Coding Challenges</h3>
<p>A great way to test a developer is to actually have them write some code for you. As they say, &#8220;the proof is in the pudding,&#8221; and even a developer who successfully answers your questions may not be able to complete the test put forth. The test can be verbal (if conducting the interview by phone), on a whiteboard (if in person) or you can give the candidate a time limit and have them email you the code. The choice is yours, just make sure that you choose one modality for all candidates. It isn&#8217;t fair comparing one candidate&#8217;s typed code to what another said on the phone, or drew on a whiteboard. Also remember that generally <span style="font-weight: bold;">typed code will be higher quality</span> than that spoken over the phone or written on a whiteboard.</p>
<p>I&#8217;ve posted a few JavaScript challenges on this blog that would make good interview questions for a JS developer. You could also adapt some of these to other languages such as C++, PHP or Java:</p>
<ul>
<li><a href="http://www.thetruetribe.com/2008/05/javascript-challenge-reverse-linked.html">Reverse a Linked List</a></li>
<li><a href="http://www.thetruetribe.com/2008/05/javascript-challenge-dispense-change.html">Dispense Change</a></li>
<li><a href="http://www.thetruetribe.com/2008/04/javascript-challenge-cardinal-numbers.html%20">Cardinal Numbers</a></li>
</ul>
<p>Other challenges include reversing a string, reversing the words in a string, finding words that occur in both files, converting a clock from digital time to degrees (e.g. for an analog clock&#8217;s hands), or generally any other relatively simple test you can come up with.</p>
<h3>Layouts and HTML/CSS</h3>
<p>For candidates doing CSS, just send them a mock-up and give them a reasonable amount of time to complete the HTML/CSS for it. You could optionally send a PSD or layered PNG, but more commonly people just send flat images. Really, the test shouldn&#8217;t be much &#8212; maybe the wireframe for a site, or a navbar, menu or UI component. You can also give them some challenge questions about explaining various CSS properties and how to use them. Challenges I&#8217;ve had in the past are:</p>
<ul>
<li>Make a banner and horizontal navbar that matches the dimensions of a wireframe</li>
<li>Make a 3-column site with a fluid-width center column</li>
<li>Create a vertical drop-down menu or horizontal flyout menu (bonus points for a cross-browser CSS-only solution, though JavaScript solutions are accepted)</li>
<li>Explain the difference between absolute and relative positioning, and what happens when you put one type of element inside another</li>
<li>Explain the difference in block and inline display</li>
<li>Explain what effect float has on elements. Does float change elements&#8217; display property, and if so, does it make it block or inline? (Answer: block)</li>
<li>Explain what effect z-index has on elements and the natural z-index order.</li>
<li>Explain CSS specificity.</li>
</ul>
<p>On this last point, CSS specificity, I find it&#8217;s fun to show a list of CSS rules and ask which rule wins out. If you know the trick how rules are calculated, it&#8217;s easy to tell:</p>
<pre class="html:nocontrols"><!-- Sample HTML code -->
&lt;!-- Sample HTML code --&gt;
&lt;p class="description" id="main"&gt;
  Some text.
  &lt;span class="special"&gt;
      Some more text.
  &lt;/span&gt;
&lt;/p&gt;</pre>
<pre class="css">/* Challenge:
 * What color is the "special" text? */

body .description span {
   color: blue;
}

p.description {
   color: red;
}

body .description .special {
   color: pink;
}

#main .special {
   color: orange;
}

#main span {
   color: green;
}</pre>
<p>For those of you unfamiliar with how CSS specificity is calculated by browsers, it is a point-based system where the selector with the highest point value wins. The three main things selectors consist of are elements, classes and ids. These are worth 1 point, 10 points and 100 points respectively. Given this knowledge, do <span style="font-style:italic;">you</span> know which rule wins out in the above example?</p>
<p>By calculating the point values of the rules, you see that the rule <span style="font-style:italic;">#main .special</span> is worth 110 points and is the winner, hence the color of the &#8220;special&#8221; text is <span style="font-style:italic;">orange</span>.</p>
<h3>Hiring People who Write Good Code</h3>
<p>Besides &#8220;just working&#8221;, the criteria for what makes good code differs from person to person, but in general, you&#8217;ll want to look for readability, useful comments, simplicity, accuracy, good formatting and code that doesn&#8217;t repeat itself. So, even if two candidates submit working solutions to a problem, you can still determine which is the better candidate by analyzing the code itself with these criteria in mind.</p>
<p>In addition to this, you may consider their talent, as opposed to their current skill in any one area. If the candidate is highly talented and passionate about the position, then they will most likely be able to learn any particular skills required for the position, within reason. Of course, talented individuals should demonstrate expertise in a number of domains already, which will give you an idea of their potential for growth in job-specific areas. You may also consider their participation in online forums, discussion groups and blogs (like this one, wink wink) related to their job field. Active participation in online communities demonstrates dedication and passion for those particular fields of interest.</p>
<p>I hope this article has been informative for interviewers and perhaps interviewees as well. Feel free to post your favorite (or least favorite) interview questions.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.thetruetribe.com%2F2008%2F05%2Fconducting-technical-interviews-for-web-developers%2F&amp;linkname=Conducting%20Technical%20Interviews%20for%20Web%20Developers"><img src="http://www.thetruetribe.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.thetruetribe.com/2008/05/conducting-technical-interviews-for-web-developers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript Challenge: Dispense Change</title>
		<link>http://www.thetruetribe.com/2008/05/javascript-challenge-dispense-change/</link>
		<comments>http://www.thetruetribe.com/2008/05/javascript-challenge-dispense-change/#comments</comments>
		<pubDate>Tue, 13 May 2008 00:55:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[MooTools]]></category>

		<guid isPermaLink="false">http://wordpress.thetruetribe.com/?p=25</guid>
		<description><![CDATA[
This challenge is to write a function that takes an amount of change and returns a String Array with the coins to dispense.
Examples:

.25 returns ['quarter']
.26 returns ['quarter', 'penny']
.30 returns ['quarter', 'nickel']
1.01 returns ['dollar', 'penny']
1.16 returns ['dollar', 'dime', 'nickel', 'penny']

One of the requirements is that this returns the least amount of units of currency as possible. [...]]]></description>
			<content:encoded><![CDATA[<div>
<p>This challenge is to write a function that takes an amount of change and returns a String Array with the coins to dispense.<span id="more-25"></span></p>
<p>Examples:</p>
<ul>
<li>.25 <em>returns</em> ['quarter']</li>
<li>.26 <em>returns</em> ['quarter', 'penny']</li>
<li>.30 <em>returns </em>['quarter', 'nickel']</li>
<li>1.01 <em>returns</em> ['dollar', 'penny']</li>
<li>1.16 <em>returns </em>['dollar', 'dime', 'nickel', 'penny']</li>
</ul>
<p>One of the requirements is that this returns the least amount of units of currency as possible. In other words, you can&#8217;t return 100 pennies or even 4 quarters when 1 dollar would suffice. This is modeled after how real-life vending machines work.</p>
<div style="float: left; width: 240px; margin-right: 18px; margin-bottom: 4px;"><a title="Land of the Vending Machines" href="http://www.flickr.com/photos/gullevek/340562157/"><img class="pc_img" src="http://farm1.static.flickr.com/166/340562157_921a63ed9e_m.jpg" alt="Land of the Vending Machines" width="240" height="160" /></a><br />
<span style="font-size:10px;">Land of the Vending Machines      By <a style="text-decoration: none;" href="http://www.flickr.com/photos/gullevek/">gullevek</a></span></div>
<p>If you want to attempt to solve this challenge yourself, <strong>read no further!</strong> The rest of the article will go on to describe my solution to this problem and some of the issues I encountered along the way.</p>
<h3 style="clear: left;">Using MooTools&#8217; <em>round()</em> Method</h3>
<p>I originally wrote my solution to this challenge without the use of JavaScript libraries. However, I ran into a common problem when dealing with dollar values, which is that I needed to round them to the 2nd decimal place. Without rounding to the 2nd place, you end up with subtle flaws in the data.</p>
<p>For instance, I was using an if() statement to check if the change remaining to dispense is greater than or equal to 0.1 (one cent). Before I added the code to round to the 2nd decimal place, the if() statement wouldn&#8217;t evaluate to true when there should be a penny left to dispense. The change remaining should have been .1, but it wasn&#8217;t entering the <span style="font-style:italic;">if(changeToDispense &gt;= 0.1)</span> statement. How could this be? Well, I was subtracting the change, but upon closer inspection, some of the values were not what I expected. When I subtract .25 from .48, I ended up with 0.22999999999999998 for instance.</p>
<p>Of course, I should have ended up with 0.23, not .022999 (repeating). But, without rounding the number, it ended up slightly less than the correct amount, introducing subtle bugs into the code. Since the full amount wasn&#8217;t being subtracted, the last penny would never be dispensed because there wasn&#8217;t a whole penny left (it was something like 0.09999999999999998). Thus, I rounded to the second decimal place and it solved the problem.</p>
<p>Using core JavaScript methods, it&#8217;s possible to work around this problem. It involves multiplying by 100, rounding and then dividing by 100. But, since most of the projects I work on use JavaScript libraries and nearly all of them have round() functions in some form or another, I decided to get a little help from a library. Specifically, I use the MooTools <em>round()</em> method for solving this problem.</p>
<p>The <em>round()</em> method takes how many places after the decimal to round to, so by calling <em>round(2)</em>, a number like 0.0999 (repeating) is converted to 0.1.</p>
<div style="float: left; margin-right: 18px; margin-bottom: 4px; width: 180px;"><span class="photo_container pc_m"><a title="Vending Machine - Japan" href="http://www.flickr.com/photos/rytc/345331437/"><img class="pc_img" src="http://farm1.static.flickr.com/132/345331437_7da8fd7cfc_m.jpg" alt="Vending Machine - Japan" width="180" height="240" /></a></span> <span style="font-size: 10px;"> Vending Machine &#8211; Japan<br />
By <a style="text-decoration: none;" href="http://www.flickr.com/photos/rytc/">rytc</a></span></div>
<p>Note that as the method is added to the prototype of the Number object (i.e. base class), it is called as an instance method of the number you want to round, <em>not</em> as a method of the Math object as with core JS methods. Compare:</p>
<ul>
<li><strong>Core JS:</strong> Math.round(1.8);</li>
<li><strong>MooTools:</strong> 1.8.round();</li>
</ul>
<h3 style="clear: left;">Designing a Solution</h3>
<p>My idea for the solution is to store a hash of the coin values keyed by their name, and then iterate over them checking if each value is higher than the amount of remaining change to dispense. For this to work, I need to iterate over them in order from highest to lowest. Otherwise, if I start in random order, it will break one of the requirements: This must return the least units of currency as possible. If I start at the penny, then it would keep dispensing pennies until there was no change left, and never get on to the other units of currency.</p>
<p>Therefore, the loop needs to <strong>iterate over the currency values in order of highest to lowest</strong>: dollar, quarter, dime, nickel, penny. Here is the hash object that I created to represent the currency values, and then we&#8217;ll discuss how to iterate over them in order:</p>
<pre class="js:nocontrols"> var money =
     'dollar': 1.00,
     'quarter': 0.25,
     'dime': 0.10,
     'nickel': 0.05,
     'penny': 0.01
 };</pre>
<p>You might think it&#8217;s as easy as using a for/in loop, but unfortunately, browser compatibility issues prevent it from being this simple. Using a for/in loop will iterate over the items but there is no guarantee of the order. Internet Explorer and Firefox use the correct order (the order of declaration) as far as I know, but Safari in particular does not follow this. So, it&#8217;s not as simple as:</p>
<pre class="js:nocontrols">function dispenseChange(changeToDispense) {
 var result = new Array();
 for (var unit in money) {
     if (money[unit] &gt; changeToDispense) result.push(unit);
 }
 return result;
}</pre>
<p>It would be nice if it were this simple, and indeed in most browsers it is. But due to obscure quirks with the order of iteration over objects of properties, we need to store the order in its own array.</p>
<div style="float: left; margin-right: 18px; margin-bottom: 4px; width: 180px;"><span class="photo_container pc_m"><a title="Asahi Beer Vending Machine: Komatsu" href="http://www.flickr.com/photos/jpellgen/444636731/"><img class="pc_img" src="http://farm1.static.flickr.com/234/444636731_42117bff1b_m.jpg" alt="Asahi Beer Vending Machine: Komatsu" width="180" height="240" /></a></span> <span style="font-size:10px;"> Asahi Beer Vending Machine: Komatsu<br />
By <a style="text-decoration: none;" href="http://www.flickr.com/photos/jpellgen/">jpellgen</a><br />
</span></div>
<h3 style="clear:both;">A Working Solution</h3>
<p>I&#8217;ve changed the <em>money</em> object to now contain two properties, a <em>values</em> hash and an <em>order</em> array.</p>
<pre class="js:nocontrols"> var money = {
     values: {
         'dollar': 1.00,
         'quarter': 0.25,
         'dime': 0.10,
         'nickel': 0.05,
         'penny': 0.01
     },
     order: ['dollar', 'quarter', 'dime', 'nickel', 'penny']
 };</pre>
<p>Now I can iterate over the <em>order</em> array and use that to key the <em>values</em> hash. It&#8217;s one extra step in the process but it doesn&#8217;t add too much bloat to the code, and it actually works (at least, in the browsers I&#8217;ve tested):</p>
<pre class="js:nocontrols">function dispenseChange(changeToDispense) {
 var result = new Array();
 while (changeToDispense.round(2) &gt;= 0.01) {
     for (var i = 0; i &lt; money.order.length; i++) {
         var value = money.values[money.order[i]]; // Number, e.g. 1.00
         if (changeToDispense.round(2) &gt;= value) {
             result.push(money.order[i]); // String, e.g. "dollar"
             changeToDispense -= value;
             break;
         }
     }
 }
 return result;
}</pre>
<p>You can test the function with logging statements:</p>
<pre class="js:nocontrols">window.addEvent('domready', function() {
 var tests = [.01, .05, .11, .27, .74, 1.08, 1.99, 2.07];
 tests.each(function(testValue) {
     console.log(testValue.toString() +
                 ': ' +
                 dispenseChange(testValue)
     );
 });
});</pre>
<h3 style="clear: left;">Improving the Implementation</h3>
<p>One area for improvement is the nested for() loop inside the while() loop. Right now it isn&#8217;t ideal, since it will waste iterations checking for currency amounts higher than the current currency. To explain what I mean, let&#8217;s look at the loop again:</p>
<pre class="js:nocontrols"> while (changeToDispense.round(2) &gt;= 0.01) {
     for (var i = 0; i &lt; money.order.length; i++) {
         // ...
         if (changeToDispense.round(2) &gt;=
             money.values[money.order[i]) {
             // dispense unit of currency
             break;
         }
     }
 }</pre>
<p>I commented out some of the implementation details so we can focus on the structure. The reason that this is sub-optimal is that after each unit of currency is dispensed, the for() loop breaks and the while() loop starts it over again. Say there is less than a dollar remaining to dispense&#8211; for each unit of currency dispensed, the for() loop will still check for a dollar.</p>
<p>To optimize this code, we&#8217;d have to only iterate over the <em>order</em> array once. This means the for() loop would be outside the while() loop, and for each unit of currency, the while() loop would continue to dispense change of that unit until the change remaining is less than the unit&#8217;s value. It would be optimized to <em>n</em> (see <a href="http://en.wikipedia.org/wiki/Big_O_notation">Big O notation</a> for details) at that point.</p>
<h3>Optimized Code</h3>
<p>Here is the <strong>new and improved</strong> code with the optimized loops:</p>
<pre class="js">var money = {
 values: {
     'dollar': 1.00,
     'quarter': 0.25,
     'dime': 0.10,
     'nickel': 0.05,
     'penny': 0.01
 },
 order: ['dollar', 'quarter', 'dime', 'nickel', 'penny']
};
function dispenseChange(changeToDispense) {

 var result = new Array();
 money.order.each(function(unit, i) {
     var value = money.values[unit]; // Number, e.g. 1.00
     while (changeToDispense.round(2) &gt;= value) {
         result.push(unit); // String, e.g. "dollar"
         changeToDispense -= value;
     }
 });
 return result;
}

window.addEvent('domready', function() {
 var tests = [.01, .05, .11, .27, .74, 1.08, 1.99, 2.07];
 tests.each(function(testValue) {
     console.log(testValue.toString() +
                 ': ' +
                 dispenseChange(testValue)
     );
 });
});</pre>
<p>An observant reader will notice that I changed the for() loop to use MooTools&#8217; each() method. The reason I did this is that we no longer need to break out of the for() loop, and I prefer the each() notation. (Thanks for recommending it, Lowell!)</p>
<p>As always, feel free to post your own solutions to this challenge in the comments.</p>
<div><span class="photo_container pc_m"><a title="The latest in Japanese vending machines" href="http://www.flickr.com/photos/fotopakismo/2228874582/"><img class="pc_img" src="http://farm3.static.flickr.com/2414/2228874582_8494e45bda_m.jpg" alt="The latest in Japanese vending machines" width="160" height="240" /></a></span></div>
<p><span style="font-size:10px;"> The latest in Japanese vending machines<br />
By <a style="text-decoration: none;" href="http://www.flickr.com/photos/fotopakismo/">El Fotopakismo</a></span></div>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.thetruetribe.com%2F2008%2F05%2Fjavascript-challenge-dispense-change%2F&amp;linkname=JavaScript%20Challenge%3A%20Dispense%20Change"><img src="http://www.thetruetribe.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.thetruetribe.com/2008/05/javascript-challenge-dispense-change/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using MooTools&#8217; Hash.Cookie API</title>
		<link>http://www.thetruetribe.com/2008/05/using-mootools-hash-cookie-api/</link>
		<comments>http://www.thetruetribe.com/2008/05/using-mootools-hash-cookie-api/#comments</comments>
		<pubDate>Thu, 08 May 2008 08:01:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[MooTools]]></category>

		<guid isPermaLink="false">http://wordpress.thetruetribe.com/?p=23</guid>
		<description><![CDATA[
MooTools makes working with cookies quite easy. Based on functions from Paul Peter Koch&#8217;s QuirksMode, the MooTools API for handling cookies is intuitive and easy to remember.
For storing simple bits of information on the browser, the Cookie methods read(), write() and dispose() are adequate. As their names imply, these read, write and delete cookies from [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://docs12b.mootools.net/Plugins/Hash.Cookie" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}"><img style="float:right; margin:0 0 10px 10px;cursor:pointer; cursor:hand;" src="http://www.thetruetribe.com/uploaded_images/doobiecookie-722766.jpg" border="0" alt="" /></a></p>
<p>MooTools makes working with cookies quite easy. Based on functions from Paul Peter Koch&#8217;s <a href="http://www.quirksmode.org/">QuirksMode</a>, the MooTools API for handling cookies is intuitive and easy to remember.<span id="more-23"></span></p>
<p>For storing simple bits of information on the browser, the <a href="http://docs12b.mootools.net/Utilities/Cookie">Cookie methods</a> <span style="font-style:italic;">read(), write()</span> and <span style="font-style:italic;">dispose()</span> are adequate. As their names imply, these read, write and delete cookies from the browser, respectively.</p>
<p>But, if you want to do something more complex, such as save a JSON string each time a method is called on the cookie, then <a href="http://docs12b.mootools.net/Plugins/Hash.Cookie">Hash.Cookie</a> is for you.</p>
<p>What&#8217;s the difference between the Hash.Cookie methods and the standard methods you say? For one, Hash.Cookie is its own module, so make sure the version of MooTools you&#8217;re using has it included. Besides that, Hash.Cookie gives you all the functionality of the Hash class, including getters/setters, <span style="font-style:italic;">each(), some(), filter(), has(), keyOf()</span> and more. For the full documentation on all Hash methods available, view the <a href="http://docs12b.mootools.net/Native/Hash/#Hash">Hash docs here</a>.</p>
<p>Here&#8217;s an example that uses the Hash.Cookie class to store <span style="font-weight:bold;">how many times a user has visited</span> the page. Note that this uses Firebug so if you don&#8217;t have it enabled, you&#8217;ll need to override <a href="http://www.thetruetribe.com/2008/04/redefining-consolelog-for-browsers.html">console.log()</a>.</p>
<pre class="js">window.addEvent('domready', function() {
    var cookie = new Hash.Cookie('test-cookie');

    var numberOfVisits = $defined(cookie.get('numberOfVisits')) ?
                         cookie.get('numberOfVisits') :
                         0;

    cookie.set('numberOfVisits', numberOfVisits + 1);

    console.log('You have visited the page ' +
                 cookie.get('numberOfVisits') +
                 ' times.');
});</pre>
<p>On line 1, we start by declaring everything to occur when the DOM is ready.<br />
For MooTools developers, this should be a familiar practice. Although we aren&#8217;t<br />
manipulating the DOM in this example, I&#8217;ve left it in, as Firebug threw an error<br />
when I tried to console.log() before the DOM was ready.</p>
<p>On line 2, we instantiate a new cookie named &#8216;test-cookie&#8217; without any options. Interestingly, this also has the effect of <span style="font-weight:bold;">loading the cookie</span> if it already exists. This means that the first time the user visits the page, it will write a cookie, but on all subsequent visits it will read a cookie. The end result is the same: we have a reference to the cookie as a hash object, and can use the methods that the Hash class provides.</p>
<p>Next, on lines 4-6, we use a <span style="font-weight:bold;">ternary operator</span> to check if &#8216;numberOfVisits&#8217; has already been written to the cookie. If so, we read it from the cookie. If not, it is initialized to 0.</p>
<p>On line 8, we increment &#8216;numberOfVisits&#8217; using the <span style="font-style:italic;">set()</span> method. Finally, we log the number of visits using Firebug&#8217;s <span style="font-style:italic;">console.log()</span>.</p>
<h3>Getters, Setters and Auto-Saving Cookies</h3>
<p>Getters and setters should be familiar to anyone versed in Java but I imagine some JavaScript developers may be unfamiliar with them. Essentially, <span style="font-style:italic;">get()</span> and <span style="font-style:italic;">set()</span> methods are provided for you to use instead of directly accessing the data. For instance, cookie.hash.numberOfVisits and cookie.get(&#8216;numberOfVisits&#8217;) both return the same data, but the former directly accesses the data while the latter uses a wrapper method.</p>
<p>There are numerous reasons to use getters/setters instead of directly accessing the data, but one practical example is the use of Hash.Cookie&#8217;s autoSave functionality. There is an <span style="font-weight:bold;">autoSave flag in the options</span> which, if enabled, will save the data after each operation on the hash. It defaults to &#8216;true&#8217; which is why I didn&#8217;t have to <span style="font-style:italic;">write()</span> the cookie in the above example.</p>
<p>Since I didn&#8217;t define a duration in the options object when instantiating the cookie (nor did I even include an options object, for that matter), it will only live for the duration of the browser. In other words, it&#8217;s a session cookie: When the user exits the browser and restarts, the cookie will be destroyed. For the cookie to live beyond the lifespan of the browser, you can specify the duration of the cookie to live (in days).</p>
<p>The other options which I omitted were <span style="font-style:italic;">domain, path</span> and <span style="font-style:italic;">secure</span>. None of those were important for my example but for some applications, setting domain- and path-specific cookies and ensuring they are only accessed over HTTPS may be necessary</p>
<p>This example is somewhat simple but I hope it has provided an introduction to using MooTools&#8217; excellent Hash.Cookie API. Good luck and enjoy a tall glass of soymilk with your Hash Cookies!</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.thetruetribe.com%2F2008%2F05%2Fusing-mootools-hash-cookie-api%2F&amp;linkname=Using%20MooTools%26%238217%3B%20Hash.Cookie%20API"><img src="http://www.thetruetribe.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.thetruetribe.com/2008/05/using-mootools-hash-cookie-api/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JavaScript Date Object</title>
		<link>http://www.thetruetribe.com/2008/05/javascript-date-object/</link>
		<comments>http://www.thetruetribe.com/2008/05/javascript-date-object/#comments</comments>
		<pubDate>Wed, 07 May 2008 00:21:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://wordpress.thetruetribe.com/?p=22</guid>
		<description><![CDATA[
In this article I will explore the use of the JavaScript date object and its methods. We won&#8217;t be using any JavaScript libraries because the existing API is quite adequate, and most libraries don&#8217;t really offer much in the way of extensions anyway.
Let&#8217;s start with displaying the current time. You can do this by using [...]]]></description>
			<content:encoded><![CDATA[<div>
<p>In this article I will explore the use of the <strong>JavaScript date object</strong> and its methods. We won&#8217;t be using any JavaScript libraries because the existing API is quite adequate, and most libraries don&#8217;t really offer much in the way of extensions anyway.<span id="more-22"></span></p>
<p>Let&#8217;s start with displaying the current time. You can do this by using the <span style="font-family: 'Courier New';">Date()</span> constructor and calling the <span style="font-family: 'Courier New';">toString()</span> method on it. If you have Firebug, open up the console and type this code:</p>
<pre class="js:nocontrols">var date = new Date();
date.toString();</pre>
<p>You&#8217;ll see that <span style="font-family: 'Courier New';">date.toString()<span style="font-family: sans-serif;"> evaluates to a string containing the current time in Greenwich Meridian Time (GMT). In my case, it is &#8220;Tue May 06 2008 16:06:39 GMT-0700 (Pacific Daylight Time).&#8221;</span></span></p>
<p><span style="font-family: 'Courier New';"><span style="font-family: sans-serif;">There are a number of other <em>to</em> methods available as well. You can paste these into the Firebug console to see what they evaluate to. I&#8217;ve put my example as a comment after each one:</span><br />
</span></p>
<ul>
<li><span style="font-family: 'Courier New';">date.toDateString(); // </span><span class="objectBox objectBox-string">&#8220;Tue May 06 2008&#8243;</span></li>
<li><span style="font-family: 'Courier New';">date.toGMTString(); // </span><span class="objectBox objectBox-string">&#8220;Tue, 06 May 2008 23:06:39 GMT&#8221;</span></li>
<li><span style="font-family: 'Courier New';">date.toLocaleDateString(); // </span><span class="objectBox objectBox-string">&#8220;Tuesday, May 06, 2008&#8243;</span></li>
<li><span style="font-family: 'Courier New';">date.toLocaleString(); // </span><span class="objectBox objectBox-string">&#8220;Tuesday, May 06, 2008 4:06:39 PM&#8221;</span></li>
<li><span style="font-family: 'Courier New';">date.toLocaleTimeString(); // </span><span class="objectBox objectBox-string">&#8220;4:06:39 PM&#8221;</span><span style="font-family: 'Courier New';"><br />
</span></li>
</ul>
<h3>Practical Applications of the JavaScript Date Object</h3>
<p>One of the most obvious applications of the date object is to display the current time, should you desire to do so. Oftentimes news websites will contain the day&#8217;s date, and sometimes they have a clock as well. For example, see <a href="http://www.bbc.co.uk/">the BBC&#8217;s homepage</a> which displays the day&#8217;s date and an analog-style clock done in Flash:</p>
<p><a href="http://www.thetruetribe.com/uploaded_images/bbc-banner-799304.jpg" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}"><img style="cursor: pointer;" src="http://www.thetruetribe.com/uploaded_images/bbc-banner-799301.jpg" border="0" alt="" /></a></p>
<p>The BBC follows the format &#8220;Tuesday 6 May 2008&#8243; for example. Let&#8217;s construct that using JavaScript:</p>
<pre class="js:nocontrols">function getFormattedDate(date) {
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    var day = days[date.getDay()];

    var months = ["January", "February", "March", "April", "May", "June",
                  "July", "August", "September", "November", "December"];
    var month = months[date.getMonth()];

    // Returns a string formatted like "Tuesday 6 May 2008"
    return day + " " +
           date.getDate() + " " +
           month + " " +
           date.getFullYear();
}

getFormattedDate(new Date());</pre>
<p>You could also accomplish this with some <strong>RegEx hackery</strong> but I think this is cleaner, albeit a bit more verbose. The benefit of doing this with RegEx is that you can use one of the existing <span style="font-family: 'Courier New';">toString()</span> methods, such as <span style="font-family: 'Courier New';">toLocaleString()</span>, and then parse the data you need from there.</p>
<p>Actually, given that the data is delimited by commas, you could accomplish this simply by splitting the returned string without the use of RegEx. Doing it that way would avoid the need to tediously specify the names of all the days and the months.</p>
<h3>Creating a Countdown Timer in JavaScript</h3>
<p>Another use case for the JavaScript date object is to count down the time remaining until a certain date. This could be the launch of a new website or product, the cut-off time for a submission, or anything else that requires notification of the time remaining until a specific date and time.</p>
<p>On a website I previously worked on, <a href="http://www.endless.com">Endless.com</a>, there is a countdown timer in the banner that notifies the customer how long they have to order to get next day shipping. This is a fun idea because it adds a little pressure for the customer to make an impulse buy as the cutoff time comes closer. I&#8217;ve seen similar uses on other e-commerce sites and it adds a nice touch, for those sites which offer next-day shipping.</p>
<p>To do something like this, I imagine you&#8217;d need two functions, one to update the HTML with the correct date string (given a date object as input), and another, possibly anonymous function that is declared with a setInterval, which decrements the current time and calls the update function. Without writing the implementation details, I imagine it would look something like this:</p>
<pre class="js:nocontrols">function updateTimeRemaining(date) {
    // implementation details for parsing data from date object
    // and updating the DOM
}

window.onload = function() {
    var interval = setInterval(function() {
        updateTimeRemaining(new Date());
    }, 1000);
};</pre>
<p>The updateTimeRemaining() function would need to be written to output the time remaining given a date object. I feel that there may be a better way to do this than creating a new Date() instance every second, however. Could we not use the same date object but decrement its time manually every second? In any case, this isn&#8217;t a full-fledged solution at this point, just an outline of one possible solution.</p>
<p>What are your favorite uses of the JavaScript date object? Do you have other use cases that I&#8217;ve left out here? Please leave them in the comments and I may even devote a whole article to them. There is quite a bit you can do with date and time and I&#8217;m always on the lookout for new uses. Hopefully these short examples will get you thinking about how you can use the JavaScript date object on <em>your</em> site.</div>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.thetruetribe.com%2F2008%2F05%2Fjavascript-date-object%2F&amp;linkname=JavaScript%20Date%20Object"><img src="http://www.thetruetribe.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://www.thetruetribe.com/2008/05/javascript-date-object/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
