<?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;  last element prototype</title>
	<atom:link href="http://www.thetruetribe.com/?s=last+element+prototype&#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>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>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>Stylize the last element in jQuery</title>
		<link>http://www.thetruetribe.com/2008/06/stylize-the-last-element-in-jquery/</link>
		<comments>http://www.thetruetribe.com/2008/06/stylize-the-last-element-in-jquery/#comments</comments>
		<pubDate>Thu, 12 Jun 2008 15:52:00 +0000</pubDate>
		<dc:creator>grandecomplex</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://wordpress.thetruetribe.com/?p=40</guid>
		<description><![CDATA[Here is how to stylize the border of the last element using jQuery.
$(document).ready(function() {
    $("table.innercart tr:last").css("border", "none");
});
You can compare to prototype by going here
]]></description>
			<content:encoded><![CDATA[<p>Here is how to stylize the border of the last element using jQuery.</p>
<pre class="code">$(document).ready(function() {
    $("table.innercart tr:last").css("border", "none");
});<span id="more-40"></span></pre>
<p>You can compare to prototype by going <a href="http://www.thetruetribe.com/2008/06/stylize-last-element-in-prototype.php">here</a></p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.thetruetribe.com%2F2008%2F06%2Fstylize-the-last-element-in-jquery%2F&amp;linkname=Stylize%20the%20last%20element%20in%20jQuery"><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/stylize-the-last-element-in-jquery/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Stylize the last element in prototype</title>
		<link>http://www.thetruetribe.com/2008/06/stylize-the-last-element-in-prototype/</link>
		<comments>http://www.thetruetribe.com/2008/06/stylize-the-last-element-in-prototype/#comments</comments>
		<pubDate>Thu, 12 Jun 2008 15:47:00 +0000</pubDate>
		<dc:creator>grandecomplex</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Prototype]]></category>

		<guid isPermaLink="false">http://wordpress.thetruetribe.com/?p=39</guid>
		<description><![CDATA[Here is an example of removing the last border in a list of elements.
Event.observe(window, "load", function() {
    $$(".homepageContainer .upcomingEvents").last().setStyle({
        border: 0
    });
});
You can compare to jQuery by going here
]]></description>
			<content:encoded><![CDATA[<p>Here is an example of removing the last border in a list of elements.</p>
<pre class="code">Event.observe(window, "load", function() {
    $$(".homepageContainer .upcomingEvents").last().setStyle({
        border: 0
    });
});<span id="more-39"></span></pre>
<p>You can compare to jQuery by going <a href="http://www.thetruetribe.com/2008/06/stylize-last-element-in-jquery.php">here</a></p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.thetruetribe.com%2F2008%2F06%2Fstylize-the-last-element-in-prototype%2F&amp;linkname=Stylize%20the%20last%20element%20in%20prototype"><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/stylize-the-last-element-in-prototype/feed/</wfw:commentRss>
		<slash:comments>0</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>LinkedList Class in MooTools</title>
		<link>http://www.thetruetribe.com/2008/05/linkedlist-class-in-mootools/</link>
		<comments>http://www.thetruetribe.com/2008/05/linkedlist-class-in-mootools/#comments</comments>
		<pubDate>Tue, 13 May 2008 22:24:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[MooTools]]></category>

		<guid isPermaLink="false">http://wordpress.thetruetribe.com/?p=26</guid>
		<description><![CDATA[A commonly used data structure in Java and other programming languages is the linked list (Wikipedia). It is similar to an array in that it is a way to store a collection of objects in sequence, however unlike an array you cannot access items in the collection by index. Instead, you access them through links [...]]]></description>
			<content:encoded><![CDATA[<p>A commonly used data structure in Java and other programming languages is the <a href="http://www.wisetome.com/splat/2007/07/19/data-structure-linked-list/#more-231">linked list</a> (<a href="http://en.wikipedia.org/wiki/Linked_list">Wikipedia</a>). It is similar to an array in that it is a way to store a collection of objects in sequence, however unlike an array you cannot access items in the collection by index. Instead, you access them through links from other items in the collection, or from the initial head or tail link (which can typically accessed with <span style="font-style: italic;">getFirst()</span> and <span style="font-style: italic;">getLast()</span> methods, respectively).<span id="more-26"></span></p>
<p><a href="http://www.wisetome.com/splat/2007/07/19/data-structure-linked-list/#more-231"><img style="float: right; margin-left: 18px; margin-bottom: 4px;" src="http://www.wisetome.com/splat/wp-content/uploads/2007/07/linked-list.png" alt="Data Structure - Linked List" width="300" /></a></p>
<p>Each item in the collection has a <span style="font-style: italic;">getNext()</span> method which returns the next item in the collection. If it&#8217;s a doubly-linked list then each item (save for the head and tail) will have both <span style="font-style: italic;">getNext()</span> and <span style="font-style: italic;">getPrevious()</span> methods.</p>
<p>In JavaScript, no such construct exists, so we&#8217;ll create one. This is mostly for academic purposes but there&#8217;s nothing to stop you from using it in real code if you&#8217;re so inclined. For the sake of this practice, we&#8217;ll just make a singly-linked list as it is a bit simpler.</p>
<p>This also provides an introduction to defining classes in MooTools. We aren&#8217;t using much MooTools-specific functionality here so it could easily be ported to another library, or even written without the use of a library. But, since I use MooTools for most of my projects, I decided to use it here. I think you&#8217;ll find defining classes in MooTools to be quite easy.</p>
<h3 style="clear: both;">The LinkedListItem Class</h3>
<p>Here is the code to define the LinkedListItem class. The LinkedListItem takes a value of any type (string, object, etc) and returns an object of type LinkedListItem, which has the original value stored as the <span style="font-style: italic;">value</span> property on the object. It also defines accessor methods for <span style="font-weight:bold;">getting/setting the next item</span> in the list. There is also an accessor method for getting the original value.</p>
<pre class="js">// This class defines an individual item in the linked list.
// The value it is instantiated with is stored in the value property,
// and is accessible via getter/setter methods.

var LinkedListItem = new Class({
   initialize: function(item) {
       this.value = item;
   },

   getNext: function() {
       return this.next;
   },

   setNext: function(item) {
       this.next = item;
   },

   getValue: function() {
       return this.value;
   }
});</pre>
<p>Read on to see how the LinkedListItem class is used by the LinkedList.</p>
<h3>Defining the LinkedList Class</h3>
<p>The LinkedList class will take an array of objects of any type and create a linked list from those objects. The linking occurs in the order of the array. So, if you call it with <span style="font-style: italic;">['a', 'b', 'c']</span> you&#8217;ll get back a linked list with <span style="font-style: italic;">a</span> as the head, and <span style="font-style: italic;">c</span> as the tail. The list will be linked like so: <span style="font-style: italic;">a -&gt; b -&gt; c</span>.</p>
<p>The LinkedList class has three methods: <span style="font-style: italic;">setFirst(), getFirst()</span> and <span style="font-style: italic;">getAll()</span>. The former two are accessor methods for changing the first element, i.e. the head. The latter is a method which returns an array of all the items in the linked list, in the order they are linked.</p>
<p>There are quite a few other methods you could implement for the LinkedList but for now, these will suffice. If you&#8217;re particularly brave and inclined to add to the class, go ahead and check out the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html">Java LinkedList docs</a> to see what other methods are available.</p>
<p>Here&#8217;s the LinkedList class I came up with:</p>
<pre class="js">var LinkedList = new Class({

   // Input: Array collection
   // An array of items to turn into a singly linked list

   initialize: function(collection) {

       this.collection = new Array();

       // Construct the linked list
       collection.each(function(item, i) {
           var item = new LinkedListItem(item);
           this.collection.push(item);

           if (i &gt; 0) {
               this.collection[i - 1].setNext(item);
           }
       }.bind(this));

       this.setFirst(this.collection[0]);
   },

   // Input: LinkedListItem item
   // Sets the head to be the given item

   setFirst: function(item) {
       this.head = item;
   },

   // Returns: LinkedListItem head

   getFirst: function() {
       return this.head;
   },

   // Returns: Array result
   // An array with all items' values, in the order they are linked

   getAll: function() {
      var result = new Array();

      result.push(this.getFirst().getValue());

      var item = this.getFirst().getNext();
      while (item) {
          result.push(item.getValue());
          item = item.getNext();
      }

      return result;
   }
});</pre>
<p>There are only two areas of the code that need explaining: constructing the list in the <span style="font-style: italic;">initialize()</span> method, and constructing an array from the list in the <span style="font-style: italic;">getAll()</span> method. I&#8217;ll touch on each to make sure it is clear what exactly is going on.</p>
<p>The initialize() method is called on each instance of the class, with the arguments given to the constructor of the class. Calling <span style="font-style: italic;">new LinkedList(['foo', 'bar'])</span> will call the <span style="font-style: italic;">initialize()</span> method with the argument ['foo', 'bar'] as well. This is an automatic function call handled by MooTools and should not be done manually, unlike Prototype where the developer must manually call the initialize() method after instantiating the class.</p>
<p>The first thing our LinkedList initialize() method does is create the <span style="font-style: italic;">collection</span> property. This is so it can store the data internally, and this property is not meant to be publicly accessible to other code.  The <span style="font-style: italic;">collection</span> array will be used to store the LinkedListItem objects created from the input array.</p>
<p>I use MooTools <span style="font-style: italic;">each()</span> method to iterate over the items in the input array (collection). For each item, I create a new LinkedListItem and add it to the <span style="font-style: italic;">collection</span> property where it will be stored. I then set the previous item&#8217;s link (if it exists) to the current item, using the <span style="font-style: italic;">setNext()</span> method.</p>
<p>Finally, once the <span style="font-style: italic;">each()</span> loop has finished iterating over all the items in the collection, I set the head link to be the first item in the array, using the <span style="font-style: italic;">setFirst()</span> method.</p>
<p>The other interesting area is the <span style="font-style: italic;">getAll()</span> method, which does basically the opposite of the initialize() method. Instead of constructing a LinkedList from an array, the <span style="font-style: italic;">getAll()</span> method <span style="font-weight:bold;">returns an array in the order of the LinkedList</span>. So you could instantiate a LinkedList in a certain order, change the order around by various <span style="font-style: italic;">setNext()</span> calls, and then call <span style="font-style: italic;">getAll()</span> and get back an array in the new order. This might not seem very useful at the moment, but bear with me and I&#8217;ll demonstrate its utility through a challenge or two.</p>
<p>The <span style="font-style: italic;">getAll()</span> method uses a <span style="font-style: italic;">while()</span> loop instead of an <span style="font-style: italic;">each()</span> loop, because we don&#8217;t know the length of the list. Even if the length of the <span style="font-style: italic;">collection</span> array is 10, for instance, we have no guarantee the list will be 10 items. The coder may have called <span style="font-style: italic;">setNext(null)</span> on the head, in which case the list would only have a length of 1. Therefore, we must use a <span style="font-style: italic;">while()</span> loop that continues as long as their are next items, in other words, as long as <span style="font-style: italic;">getNext()</span> on the current item is not null.</p>
<p>Inside the <span style="font-style: italic;">while()</span> loop, we simply add the current item to the result array and then redefine the item variable to point to the next item. After the loop finishes, we return the result, which is an array in the order that the list is linked.</p>
<p>You can test that this works by instantiating a LinkedList and calling <span style="font-style: italic;">getAll()</span> on it.</p>
<pre class="js:nocontrols">window.addEvent('domready', function() {

   var list = new LinkedList(['a', 'b', 'c', 'd',
                              'e', 'f', 'g', '1',
                              '2', '3', '4', '5']);

   console.log(list.getAll());

   // RESULT:
   // a,b,c,d,e,f,g,1,2,3,4,5
});</pre>
<h3>LinkedList Challenge</h3>
<p>Next up, a LinkedList challenge! Can you write code that <span style="font-weight: bold;">reverses a linked list</span> in place, without creating a new array?</p>
<p>My next post will provide an answer, but in the meantime, give it a try. To make it clear, the challenge is to reverse a singly-linked list, using either the LinkedList class defined here or your own implementation, in place. That is, without creating another array, hash or other data structure to store the data in the list temporarily before writing it again.</p>
<p>This is the expected outcome:</p>
<pre class="js:nocontrols">   var list = new LinkedList(['a', 'b', 'c', 'd',
                              'e', 'f', 'g', '1',
                              '2', '3', '4', '5']);

   console.log('Forward: ' + list.getAll());
   console.log('Backward: ' + reverseLinkedList(list));

   // RESULT:
   //
   // Forward: a,b,c,d,e,f,g,1,2,3,4,5
   // Backward: 5,4,3,2,1,g,f,e,d,c,b,a</pre>
<p>I should also mention that you can&#8217;t access the <span style="font-style: italic;">collection</span> array inside the linked list directly. Otherwise, you could just do something like this:</p>
<pre class="js:nocontrols">function reverseLinkedList(list) {
   return list.collection.reverse();
}</pre>
<p>That would be a cheap, and is not an acceptable solution. This challenge is to reverse the list in place, so your only choice for starting is to call getFirst() on the list:</p>
<pre class="js:nocontrols">function reverseLinkedList(list) {
   var head = list.getFirst();
}</pre>
<p>This challenge was given to me in Java by my mentor at Amazon, Chris. It took me a good 45 minutes to solve the first time (though Chris made me solve it on a whiteboard, which is always more difficult for me than typing it up). Good luck and stay tuned for the next post which will offer a solution to this challenge.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.thetruetribe.com%2F2008%2F05%2Flinkedlist-class-in-mootools%2F&amp;linkname=LinkedList%20Class%20in%20MooTools"><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/linkedlist-class-in-mootools/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Truncating Text with JavaScript</title>
		<link>http://www.thetruetribe.com/2008/05/truncating-text-with-javascript/</link>
		<comments>http://www.thetruetribe.com/2008/05/truncating-text-with-javascript/#comments</comments>
		<pubDate>Tue, 06 May 2008 02:03:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Prototype]]></category>

		<guid isPermaLink="false">http://wordpress.thetruetribe.com/?p=20</guid>
		<description><![CDATA[Since Alex posted an article on truncating text with Prototype, I thought I would write an article on truncating text without the help of a JavaScript framework.
I won&#8217;t define a class like in his example, but I will try to provide the same functionality, and perhaps add some functionality as well. This code will search [...]]]></description>
			<content:encoded><![CDATA[<p>Since Alex posted an article on <a href="http://www.thetruetribe.com/2008/05/how-to-truncate-in-prototype.html">truncating text with Prototype</a>, I thought I would write an article on truncating text without the help of a JavaScript framework.<span id="more-20"></span></p>
<p>I won&#8217;t define a class like in his example, but I will try to provide the same functionality, and perhaps add some functionality as well. This code will search for all HTML elements with the class &#8216;truncate&#8217;, or with another className if one is specified, and will truncate to the nearest word less than the character-count you specify. It also defaults to appending &#8216;&#8230;&#8217; (the ellipsis) but you can override this with an empty string as the third optional parameter, if you prefer not to have anything appended.</p>
<p>Note: I wrote in the comments on Alex&#8217;s article that you may want to add ellipsis to his code. I realized after reading the <a href="http://www.prototypejs.org/api/string/truncate">Prototype API docs</a> that in fact, this is exactly what it does by default. Unless you specify an override with an optional parameter, the Prototype truncate() method will automatically add an ellipsis at the end of the string it returns.</p>
<p>Here is my implementation of the truncate() function, without the use of JavaScript libraries:</p>
<pre class="js:nocontrols">// Input parameters:
// String text, [Number length, String ellipsis]
//
// Returns:
// String text

function truncate(text, length, ellipsis) {    

    // Set length and ellipsis to defaults if not defined
    if (typeof length == 'undefined') var length = 100;
    if (typeof ellipsis == 'undefined') var ellipsis = '...';

    // Return if the text is already lower than the cutoff
    if (text.length &lt; length) return text;

    // Otherwise, check if the last character is a space.
    // If not, keep counting down from the last character
    // until we find a character that is a space
    for (var i = length-1; text.charAt(i) != ' '; i--) {
        length--;
    }

    // The for() loop ends when it finds a space, and the length var
    // has been updated so it doesn't cut in the middle of a word.
    return text.substr(0, length) + ellipsis;
}</pre>
<h3>Truncating Text by Class Name</h3>
<p>In Alex&#8217;s example, he wrote a class in Prototype that you initialize with an array of HTML elements. For this example, we&#8217;ll register an event handler to the window onload that will look for <span style="font-weight:bold;">all elements with the class &#8216;truncate&#8217;</span> and truncate them to our specifications.</p>
<pre class="js:nocontrols">window.onload = function() {
    var elements = document.getElementsByClassName('truncate');
    for (var i = 0; i &lt; elements.length; i++) {
        elements[i].innerHTML = truncate(elements[i].innerHTML, 100);
    }
}</pre>
<p>It&#8217;s basically doing the same thing as in Alex&#8217;s example, except that I&#8217;m using the window.onload event instead of the custom &#8216;domready&#8217; event (called <a href="http://www.prototypejs.org/api/document/observe">dom:loaded in Prototype</a>) which triggers much quicker. If you are using a framework, then use one of the custom &#8216;domready&#8217; events because they trigger as soon as the DOM is accessible for manipulation, whereas the traditional window.onload event waits to fire until each and every image is finished downloading. Good grief!</p>
<p>Note that this example will only work in Firefox 3 or Safari 3, as other browsers do not natively support document.getElementsByClassName. You could just implement your own getElementsByClassName function like so:</p>
<pre class="js">function getElementsByClassName(className) {
    // RegExp from http://www.robertnyman.com
    //             /2005/11/07/the-ultimate-getelementsbyclassname/

    var match = new RegExp('(^|\\\\s)' + className + '(\\\\s|$)');

    // All elements which match are added to the array
    var matchingTags = new Array();

    var allTags = document.getElementsByTagName('*');
    for (var i = 0; i &lt; allTags.length; i++) {
        if (match.test(allTags[i].className)) {
            matchingTags.push(allTags[i]);
        }
    }
    return matchingTags;
}

window.onload = function() {
    var elements = getElementsByClassName('truncate');
    for (var i = 0; i &lt; elements.length; i++) {
        elements[i].innerHTML = truncate(elements[i].innerHTML, 100);
    }
}</pre>
<p>Make sure that you only give the &#8216;truncate&#8217; class to elements whose <span style="font-weight:bold;">only child is a text node</span>. If the element has other HTML children then this won&#8217;t work correctly. It&#8217;s possible to code around this but for the sake of this example, let&#8217;s just keep it simple. Here are two examples that show proper and improper use:</p>
<p><span style="font-weight:bold;">This is OK:</span></p>
<pre class="html:nocontrols">&lt;span class="truncate"&gt;some text &lt;/span&gt;</pre>
<p><span style="font-weight:bold;">This is not OK</span>:</p>
<pre class="html:nocontrols">&lt;span class="truncate"&gt;&lt;span&gt;some text &lt;/span&gt;&lt;/span&gt;</pre>
<p>As always, feel free to post in the comments with any questions or alternative suggestions for the code. This is a fairly simplistic implementation and truth be told, if you&#8217;re using a JavaScript library (which it seems most people are these days) then this may not be too relevant for you. But, hopefully it has been informative to explore this library-free, albeit simple, implementation.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fwww.thetruetribe.com%2F2008%2F05%2Ftruncating-text-with-javascript%2F&amp;linkname=Truncating%20Text%20with%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/2008/05/truncating-text-with-javascript/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
