tag:blogger.com,1999:blog-60697457905392219612008-07-23T16:26:17.293-07:00The True TribeJonah Dempcyhttp://www.blogger.com/profile/02468258890873289795noreply@blogger.comBlogger38125tag:blogger.com,1999:blog-6069745790539221961.post-69884299053264263032008-07-14T16:14:00.001-07:002008-07-14T16:17:44.917-07:00The True Tribe Redesign Coming SoonAs you may have noticed, The True Tribe has been on a bit of a hiatus for articles over the past couple of weeks. This is because we have been devoting all of our effort into developing an entirely new site, built with Joomla rather than our current implementation on Blogger's platform.<br><br>The new site will be more than just a web development blog-- it aims to provide resources such as articles, tutorials/walkthroughs, messageboards and community features.<br><br>After much deliberation, we decided on Joomla as the framework for the back end. We will be using MooTools for the front end.<br><br>Right now we are finalizing design, and simultaneously setting everything up in the back end. I estimate the new site will launch in August or September. In the meantime, check out our backlog of existing articles or peruse some of the links in the sidebar.<br><br>Thanks for reading!<br>-JonahJonah Dempcyhttp://www.blogger.com/profile/02468258890873289795noreply@blogger.comtag:blogger.com,1999:blog-6069745790539221961.post-83805581876855018422008-06-18T01:43:00.000-07:002008-06-18T03:55:44.722-07:00Installing Synergy For Linux and Windows<p><a href="http://synergy2.sourceforge.net/">Synergy</a> is a great app that allows you to control your Linux and Windows computers via a single keyboard and mouse. You can plug in the keyboard/mouse to either Linux or Windows machines and fluidly switch between computers just as easily as you would switch between monitors in a dual-monitor set up.</p><p>Here is a description and image from the Synergy site which demonstrates this functionality:</p><p> </p><blockquote><p>In this example, the user is moving the mouse from left to right. When the cursor reaches the right edge of the left screen it jumps instantly to the left edge of the right screen. </p><p> </p><center><img src="http://synergy2.sourceforge.net/images/warp.gif" /></center> <p> You can arrange screens side-by-side, above and below one another, or any combination. You can even have a screen jump to the opposite edge of itself. Synergy also understands multiple screens attached to the same computer. </p></blockquote><p></p><p>I've been using it for a couple of years now and I find it an invaluable addition to the arsenal of any developer who works in both Windows and Linux. I built a new computer over the weekend and finished installing Ubuntu 8.08 Gutsy Gibbon tonight. One of the first things I did was install Synergy. Previously, I set it up on Red Hat Enterprise, but either way, the set up is pretty straightforward.</p><p><span style="font-weight: bold;">Let's get started</span> installing Synergy, shall we? The Windows set up is easier because it has a GUI. In Windows, go to the <a href="http://synergy2.sourceforge.net/">Synergy SourceForge</a> page to download the latest release (version 1.3.1 as of this writing). Here's the download link if you don't want to be bothered with navigating the SourceForge page:</p><ul><li> <a href="http://downloads.sourceforge.net/synergy2/SynergyInstaller-1.3.1.exe?modtime=1143984577&big_mirror=0">Download SynergyInstaller-1.3.1.exe from SourceForge</a></li></ul>Once it's downloaded, install it and open the <span style="font-style: italic;">synergy.exe</span> file to launch the program.
</p><p>
I prefer to set Windows as the client and Linux as the slave, although it was recommended in a forum post to do the opposite in Windows Vista. Regardless, I haven't had issues with Vista or XP in either configuration.</p><p>
For now, let's assume your keyboard and mouse is hooked into the Linux box and you want to make Windows the slave (client). To do this, simply click the radio button next to <span style="font-style: italic;" class="code">Use another computer's shared keyboard and mouse (client)</span>. Then, enter the Linux computer's host name next to <span style="font-style: italic;" class="code">Other Computer's Host Name</span>. For me, this is 'ubuntu' but you may have been more creative with your host name.
</p><p>
We're not quite ready to test it yet, so leave this window open and go back to Linux for a moment. In Ubuntu, install Synergy by typing:
</p><p>
<span style="font-family: courier new;">sudo apt-get install synergy</span>
</p><p>
If you prefer doing things in the console, then you can manually create the config files. Otherwise, you can use a GUI called QuickSynergy to get up and running. Here's how to do either way:</p><p>
<span style="font-weight: bold;">The manual way</span> might take a little longer, or not, depending on how good you are with command line interfaces. To install it manually, first you must create a configuration file called <span style="font-style: italic;">synergy.conf</span> that looks like this:
</p>
<pre> section: screens
<span class="arg">screen1</span>:
<span class="arg">screen2</span>:
end
section: links
<span class="arg">screen1</span>:
right = <span class="arg">screen2</span>
<span class="arg">screen2</span>:
left = <span class="arg">screen1</span>
end
</pre><p>
You can place the config file in /etc/ or /usr/local/etc/ (whichever you prefer). Just make sure it is somewhere in the environment PATH for convenience's sake.
</p><p>
For me, this file says:
</p>
<pre> section: screens
ubuntu:
laptop<span class="arg"></span>:
end
section: links
<span class="arg">screen1</span>:
right = <span class="arg">laptop
</span> <span class="arg">screen2</span>:
left = ubuntu<span class="arg"></span>
end
</pre><p>
My laptop is, of course, named 'laptop' -- again, feel free to use more imaginative names (as long as it is actually the name of the computer). It isn't necessary to use the name of the computer as the name of the screen but it requires extra configuration otherwise. (See <a href="http://synergy2.sourceforge.net/">the official documentation</a> for more information on this).</p><p>
Now that you've created the file, you're ready to launch Synergy. Give it a try with this line:</p><p>
<pre> synergys -f --config synergy.conf
</pre><p>Assuming it starts correctly, jump back to Windows and click 'Test' in Synergy there. It should say that it connected OK and everything is fine and dandy. If that's the case, then just click 'Start' and you're done. If not, visit <a href="http://synergy2.sourceforge.net/">the docs page</a> and scroll towards the bottom to troubleshoot the issue.</p><p>
<span style="font-weight: bold;">If you prefer graphically configuring Synergy</span>, that's an option, too. I guess I should have put the GUI solution first for us lazy developers, but it's good to be familiar with the non-graphical way anyway. I know that I managed to mess up my config file using the GUI and had to dive in to it regardless.</p><p>
That being said, the GUI (called QuickSynergy) is very straightforward and easy to use. To install QuickSynergy, type the following in a Linux terminal:
</p><p>
<span style="font-family: courier new;">sudo apt-get install quicksynergy</span>
</p><p>
Once it's installed, you can type <span style="font-style: italic;">quicksynergy</span> to launch it (add & at the end if you want to retain your terminal window) and a window will popup that allows you to configure Synergy, either as host or client.
</p><p>
<center><img src="http://quicksynergy.sourceforge.net/imagens/QuickSynergyLinux.png" alt="" align="middle" border="0" /></center> </p><p>
The default tab which opens is for host, and all you have to do is enter the correct screen names and then start it. For me, my Linux desktop (named 'ubuntu') is on the left and my Vista laptop (named 'laptop') is on the right, so I just made sure that the fields to the left and right of the computer image said 'ubuntu' and 'laptop', respectively.</p><p>
QuickSynergy is theoretically easier to use than the command line way detailed above, so I won't go into much depth here. If you get stuck with QuickSynergy, either try the command line way, or visit the <a href="http://quicksynergy.sourceforge.net/">QuickSynergy SourceForge site </a>to see screenshots and example configurations.
</p><p>
<span style="font-weight: bold;">Extra Features:
</span></p><ul><li>Synergy has the ability to auto-sync starting and stopping of screensavers
</li><li>You can copy and paste between Linux and Windows (this is a huge time-saver!)
</li><li>Easily lock the mouse/keyboard to the current screen by toggling scroll lock (assignable to any other key)
</li></ul>Jonah Dempcyhttp://www.blogger.com/profile/02468258890873289795noreply@blogger.comtag:blogger.com,1999:blog-6069745790539221961.post-19052402915496010332008-06-17T00:50:00.001-07:002008-06-17T01:26:56.761-07:00What's New in MooTools 1.2<p>I'm happy to announce that MooTools (<a href="http://en.wikipedia.org/wiki/MooTools">Wikipedia link</a>) has released version 1.2 of their excellent JavaScript library. MooTools, which stands for 'My Object Oriented Tools', was developed in 2006 by <a href="http://mad4milk.net/">Valerio Proietti</a> and <a href="http://mootools.net/developers">his colleagues</a>. It evolved out of <a href="http://en.wikipedia.org/wiki/Moo.fx">Moo.fx</a>, a lightweight effects library which plugged into the Prototype framework. It was similar, although smaller (and in my opinion, better) than the scriptaculous library. Moo.fx has now been fully integrated into the MooTools library and is not being developed further at this time.</p><p> Even before MooTools' 1.0 release on January 29, 2007, it had garnered quite a bit of buzz. There were even <a href="http://snook.ca/archives/javascript/mootools_r83_cheatsheet/">cheat sheets</a> created for the beta MooTools library.</p>
<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://mootools.net/"><img style="float:right; margin:0 0 10px 10px;cursor:pointer; cursor:hand;" src="http://mootools.net//assets/images/mootools.png" border="0" alt="" /></a>
<p>Thus, it is with great excitement that I announce a new version of this marvelous framework, with a great deal of improvements and additions to the codebase. I've been using 1.2 beta for quite a while and I think the official release is mostly a bug fix of the beta, so if you've been following this blog, chances are you've already been exposed to some of the new features in 1.2. Regardless, here's a full list of features and enhancements you'll find in the new release:</p>
<ul>
<li><a href="http://blog.mootools.net/2008/2/12/what-s-new-in-1-2-swiff">Swiff</a>, support for working with Flash SWF files, similar to the <a href="http://code.google.com/p/swfobject/">swfobject</a> library</li>
<li><a href="http://blog.mootools.net/2008/1/22/Element_Storage">Element storage</a> allows you to store data in custom properties on HTML elements without leaking memory in IE</li>
<li>Overhaul of Fx classes with <a href="http://blog.mootools.net/2007/10/23/The_Best_Javascript_Effects_Now_Even_Better">many improvements</a>, including creating a <a href="http://docs.mootools.net/Fx/Fx.Tween">Tween</a> class to create reusable animation tweens</li>
<li>Overhauled Ajax requests; renamed Ajax class to <a href="http://docs.mootools.net/">Request </a>, with JSON and HTML subclasses (for easily handling their respective data formats as Ajax responses)</li>
<li><a href="http://docs.mootools.net/Element/Element.Dimensions">Element.Dimensions</a> - makes it a breeze to get width, height, x/y coordinates of an element (either relative to document or to positioning context) and scroll height/width</li>
<li>Created a <a href="http://docs.mootools.net/Core/Browser">Browser</a> class to store browser, platform and feature information (e.g. whether the browser supports XPath or not). Before, browser info was stored on the window object. Also, this release renamed the properties from browser names to rendering engine names, e.g. <span style="font-style:italic;">trident4</span> instead of <span style="font-style:italic;">ie6</span>.</li>
<p>In addition to the changes to the API and codebase, the following changes occured as well:</p>
<li>MooTools now adheres to <a href="http://blog.mootools.net/2007/10/20/what-s-new-in-1-2-spec-runner">behavior driven development</a> using specs</li>
<li><a href="http://blog.mootools.net/2007/10/8/what-s-new-in-1-2-the-hash">The Hash Object</a> - with <span style="font-style:italic;">get, put, each, some</span> and a whole lot of other methods for manipulating data in a hash</li>
<li>MooTools developed using <a href="http://blog.mootools.net/2008/6/12/mootools-1-2-it-s-official">Git</a> instead of Subversion now - this will only affect you if you're used to grabbing code from svn (or if you're a contributor!)</li>
<li>MooTools uses <a href="http://mootools.lighthouseapp.com/">Lighthouse</a> instead of Trac for bug tracking now</li></ul>
<p>In light of all these improvements to an already excellent library, I think it's apparent that MooTools is really growing up and coming into its own. It's a force to be reckoned with and certainly a heavyweight contender against Prototype, jQuery, YUI and others.</p>
<p>I hope you've enjoyed this brief overview of some of the new features in MooTools 1.2. Now get out there and start coding!</p>
<h5>Related links:</h5>
<ul>
<li><a href="http://www.mootools.net">MooTools homepage</a></li>
</ul>
<h5>Docs and Demos</h5>
<ul>
<li><a href="http://docs.mootools.net">1.2 Documentation</a></li>
<li><a href="http://demos.mootools.net">1.2 Demos</a> </li>
</ul>
<h5>Compatibility</h5>
<ul>
<li><a href="http://mootools.net/js/mootools-compat-core.js">Core Compatibility File</a></li>
<li><a href="http://mootools.net/js/mootools-compat-more.js">Plugin Compatibility File</a></li>
</ul>
<h5>Git Repositories</h5>
<ul>
<li><a href="http://github.com/mootools/mootools-core">Core Repository</a></li>
<li><a href="http://github.com/mootools/mootools-more">Plugin Repository</a>
</ul>
<h5>Bug Tracking</h5>
<ul>
<li><a href="http://mootools.lighthouseapp.com/">MooTools at Lighthouse</a></li>
</ul>
<h5>MooTools User Groups</h5>
<ul>
<li><a href="http://groups.google.com/group/mootools-users/">MooTools Users at Google Groups</a></li>
<li><a href="irc://irc.freenode.org/#mootools">#mootools on Freenode</a></li>
</ul>Jonah Dempcyhttp://www.blogger.com/profile/02468258890873289795noreply@blogger.comtag:blogger.com,1999:blog-6069745790539221961.post-29154364680758280962008-06-15T23:01:00.001-07:002008-06-19T17:02:37.800-07:00Javascript image rotator viewer<a href="See a demo at http://www.alexgrande.com">See a demo at http://www.alexgrande.com</a>
<br />
It is the images on the top right.
<br />
I wrote this in Object Oriented format so you can use it again again on page.
<br />
Javascript:<br />
<pre name="code" 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 < 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>
<br />
<br />
This is to load it on the window object and create an instance of the viewer
<br />
<pre name="code" 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>
<br />
<br />
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
<br />
<br />
HTML:
<br />
<pre name="code" class="html">
<div id="gallery">
<ul id="index_thumbnail_display">
<li>
<a href="images/index/fernlarge.jpg" >
<img class="thumbnailDefault" src="images/index/fernthumb.jpg" alt="A picture of a fern just as it is unraveling in front of a log." />
</a>
</li>
<li>
<a id="partythumb" href="images/index/partylarge.jpg" >
<img class="thumbnailDefault" src="images/index/partythumb.jpg" alt="Downtown Seattle at night." />
</a>
</li>
<li>
<a id="alexthumb" href="images/index/alexlarge.jpg" >
<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." />
</a>
</li>
<li>
<a href="images/index/trucks.jpg" >
<img class="thumbnailDefault" alt="Trucks lined up in Sodo in Seattle at night." src="images/index/trucksthumb.jpg" />
</a>
</li>
</ul>
<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." />
</div>
</pre>
<br />
<br />
CSS:
<br />
<pre name="code" 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>Alex Grandehttp://www.blogger.com/profile/01750789401997148077noreply@blogger.comtag:blogger.com,1999:blog-6069745790539221961.post-68078775185246528312008-06-12T23:10:00.001-07:002008-06-12T23:16:23.624-07:00Saving State: What To Do When Users Leave<p>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 the user leaves and returns to the page,
will the application state be preserved?</p>
<p>The effects of losing application state can range from
minor annoyances like losing what page you're on, to
all-out frustration after losing a carefully-typed message
because you accidentally triggered the browser's back
button. (It's easier than you think-- hitting backspace
when the document is in focus triggers the back button in
most browsers). Couple this with the fact that some users
may expect pages to save form data, because of their prior
experience to that effect, and it becomes apparent that a
robust strategy for preserving application state must be
devised.</p>
<p>Browsers automatically save data entered into form
fields, but all JavaScript variables are lost when the user
leaves the page. Furthermore, any form fields that were
created by JavaScript will also be lost. So, for all but
the most simple applications, JavaScript must have a
strategy for saving state that deals with these
limitations.</p>
<p>Some sites like <a href=
"http://www.thesixtyone.com"><em>thesixtyone.com</em></a>
reside entirely on a single page and capture users' back
button clicks with named anchors. But, try writing a wall
post on Facebook and you'll find that it does not save the
post if you leave the page. Accidentally pressing backspace
is all too easy in cases like this where typing is
involved, which is why sites like Gmail and Blogger warn
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
message to the return value of the
<em>window.onbeforeunload</em> event handler. The user will
be presented with two choices, <em>OK</em> and
<em>Cancel</em>, along with a custom message of your
choosing.</p>
<p>In the following example, we regsiter an anonymous
function as the event handler for
<em>window.onbeforeunload</em>, and add our own custom
message:</p>
<h5>Using <em>window.onbeforeunload</em> to confirm if a
user wants to leave the page (<a href=
"/examples/saving-state/example-1.html">example 1</a>)</h5>
<pre name="code" class="js:nocontrols">
window.onbeforeunload = function() {
return "You will lose any unsaved information.";
};
</pre>
<p>The browser displays your custom message, given in the
return statement of the <em>onbeforeunload</em> event
handler, along with the browser default message. In
Firefox, the result is:</p>
<blockquote>
Are you sure you want to navigate away from this
page?<br />
You will lose any unsaved information.<br />
Press OK to continue, or Cancel to stay on the current
page.
</blockquote>
<h3>Retaining Data When Users Do Leave the Page</h3>
<p>You may opt to silently save the user's data when they
leave the page. This may give a better user experience
since they are not confronted with a choice, and their data
is saved automatically.</p>
<p>This is one of the times where Ajax comes in handy.
However, there are also other ways to do this without using
Ajax, such as cleverly storing information in named anchors
or hidden form fields. We'll examine each of these
practices in more depth, but suffice it to say that the
hidden form fields approach works better for conventional
websites that are spread across many pages, whereas storing
data in named anchors is better for single-page, pure
JavaScript applications.</p>
<p>It turns out that while you could (and should) save
state to the server using Ajax, for some cases you will
want to avoid Ajax altogether and use a simpler,
clientside-only model.</p>
<h3>Using Hidden Form Fields to Save State</h3>
<p>As mentioned, all JavaScript objects are lost when the
user leaves or refreshes the page. But, browsers will
retain data in form fields, provided that the form elements
were not generated using JavaScript. Given this limitation,
it is necessary to save JavaScript variables (or the
serialized JSON strings of such objects) to hidden form
fields if they need to be retained.</p>
<p>Here is a basic example showing how variables can be
stored to hidden form fields and restored on page load:</p>
<pre name="code" class="html:nocontrols">
<input id="saved-data" type="hidden" />
</pre>
<h5>Saving data in hidden form fields (<a href=
"/examples/saving-state/example-2.html">example 2</a>)</h5>
<pre name="code" 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're saving is one string
from the user. But what about cases where we need to save
many different values? For instance, what if we're using
object-oriented code and have numerous nested objects
within objects we need to store? At times like this,
<strong>serializing objects with JSON</strong> is the
easiest way to store the data. Without using JSON, you'd
have to create a hidden form field for each value you want
to save, whereas JSON can create string representations of
complex data structures that you can easily <em>eval</em>
back into JavaScript objects once they're fetched from the
DOM.</p>
<h3>So What is JSON, Anyway?</h3>
<p>JSON (pronounced "Jason"), short for <em>JavaScript
Object Notation</em> is a lightweight, human- and
machine-readable way to represent the string serializations
of objects. These strings can be evaluated back into
JavaScript objects as needed. For instance, say I create a
JavaScript object to represent a person (in this case,
me):</p>
<pre name="code" 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
follows:</p>
<pre name="code" 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
point, you can simply eval the JSON string:</p>
<pre name="code" 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've written JavaScript using object literal syntax
before, this should be familiar to you. The only minor
difference between JSON and the standard JavaScript object
literal syntax is that JSON requires quotes around key in a
key/value pair. So, <em>name</em> is a valid JavaScript key
but in JSON it would have to be <em>'name'</em>. (Note: It
doesn't matter if you use single- or double-quotes, as long
as they are matched).</p>
<h3>Stringifying Objects in JSON</h3>
<p>To use JSON, it's necessary to include a library of JSON
methods. Don't worry, the library is quite small. The
entire thing shouldn't be more than 2k and can be obtained
from <a href="http://www.json.org/js.html">json.org</a>.
Eventually, the JSON methods will be included as part of
the core JavaScript language, but for the time being, we're
left to use the methods provided by json.org or those found
in libraries such as MooTools, Prototype and jQuery.</p>
<p>Depending on the library used, the method names for
serializing an object into a JSON string are different.
But, they are all used in rather similar fashion. For now,
we'll assume you're using the library from <a href=
"http://www.json.org/js.html">json.org</a> and use the
method names provided in its API.</p>
<h5>Saving complex JavaScript data structures as JSON
strings (<a href="/examples/saving-state/example-3.html">example 3</a>)</h5>
<pre name="code" 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
we saved a string. The only difference is that in this
case, the string is a representation of a complex
JavaScript object. In fact, you can save the entire state
of your application in one JSON string, as long as the
application state is completely stored as properties of a
single object. There are a few minor gotchas, such as
having to add parentheses around the JSON string when
evaluating it. But, overall this is a clean and
straightforward approach that is very useful when complex
data structures must be retained.</p>
<h3>Using Named Anchors to Save State</h3>
<p>An alternate option for retaining state is to not
actually let the user leave the page at all. Rather, when
following links on the site, update the named anchor
(everything after the number sign in a URL), instead of
changing the actual document being displayed.</p>
<p>The problem that this is trying to solve is the fact
that Ajax applications will normally break the back button.
A user loads the application on the homepage and clicks to
visit a different page, but since the new page is loaded in
via Ajax, the browser URL doesn't change. Then the user
clicks the back button and leaves the application
altogether-- not the intention of the user, who just wanted
to get back to the homepage.</p>
<p>Storing data in named anchors offers a solution to this
problem. Each time the application state changes,
JavaScript updates the named anchor with a token
representing the application state. When the page is
loaded, data is read from the named anchors and the state
can be restored.</p>
<p>Say you're on the homepage of an ecommerce Ajax
application and click on a product you'd like to view.
Instead of changing URLs to the detail page, the
application loads in new data with Ajax. So, when a user
clicks on the new Brad Mehldau CD for instance, instead of
going to a different URL (yoursite.com/brad-mehldau/) the
document URL remains the same, but JavaScript updates the
named anchor: yoursite.com/#brad-mehldau.</p>
<p>One site which does this unbelievably well is <a href=
"http://www.thesixtyone.com"><em>thesixtyone.com</em></a>
(Thanks, Derek!). The entire site resides in one document,
truly a rich JavaScript application if I've ever seen one.
But, despite the fact that the entire application is
contained in a single document URL, due to clever use of
named anchors, the site has full back button support and
you can even email working links to friends.</p>
<p>Implementing code to save state in named anchors is out
of scope for this article, but you can see how it is
somewhat similar to saving data in hidden form fields. In
this case, there are a few more issues to mitigate and it's
somewhat tricky, but the reward is an Ajax site with fully
functional back button support and the ability to share
links -- worth all the effort, in my book.</p>
<h3>So What Use is Ajax, Then?</h3>
<p>Since we've made it this far, you might think that there
is no use for Ajax in all this. Actually, Ajax is great for
saving state to the server, especially for saving data
beyond the lifespan of the browser session. Ajax can be
used to save messages periodically (like how Gmail and
Google Docs automatically save on a timer every few
minutes). It can also be used to send data when the user
leaves the page by capturing the <em>onbeforeunload</em>
event, but this is unreliable and I would not depend on
this Ajax request to complete. Instead, try to save the
data before the user attempts to leave the page, by either
firing the Ajax request on a timer or another event on the
page (leaving focus on a form element, for example).</p>
<p>Some frameworks like Prototype have serialize() methods
that return URL query string representations of objects.
This is perfect for saving data through GET requests. Yes,
GET requests have a 2000-character limit and other
limitations, but in most cases this won't be an issue. Even
without helper methods to serialize objects, it's a fairly
simple matter to construct an Ajax request that will save
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
sure they want to leave a page when they are entering
information, but it's even better to silently save that
information for them. (Arguably you would want to do both,
like how Gmail and Blogger save state <em>and</em> ask
users if they are sure they want to leave the page). There
are many different ways to save state, some purely
client-side and others relying on saving data to the server
with Ajax. The solutions which save data to the server are
suitable for times when the data needs to be saved beyond
the browsing session.</p>
<p>Of the two client-side solutions explored, hidden form
fields and named anchors, the former is more suitable for
conventional websites spanning many pages while the latter
better suits single-page Ajax applications. Using named
anchors also has the added benefit of allowing users to
bookmark and send links to the JavaScript application in
various states, and the state is preserved beyond the
browsing session.</p>
<p>Whatever strategy you follow, your users will thank you
for the time saved and frustration avoided of having to
re-enter lost information.</p>Jonah Dempcyhttp://www.blogger.com/profile/02468258890873289795noreply@blogger.comtag:blogger.com,1999:blog-6069745790539221961.post-52793282495746583982008-06-12T08:52:00.000-07:002008-06-12T08:55:20.268-07:00Stylize the last element in jQueryHere is how to stylize the border of the last element using jQuery.
<pre class="code" name="js">
$(document).ready(function() {
$("table.innercart tr:last").css("border", "none");
});
</pre>
You can compare to prototype by going <a href="http://www.thetruetribe.com/2008/06/stylize-last-element-in-prototype.php">here</a>Alex Grandehttp://www.blogger.com/profile/01750789401997148077noreply@blogger.comtag:blogger.com,1999:blog-6069745790539221961.post-16296011606562364262008-06-12T08:47:00.000-07:002008-06-12T08:56:11.815-07:00Stylize the last element in prototypeHere is an example of removing the last border in a list of elements.
<pre class="code" name="js">
Event.observe(window, "load", function() {
$$(".homepageContainer .upcomingEvents").last().setStyle({
border: 0
});
});
</pre>
You can compare to jQuery by going <a href="http://www.thetruetribe.com/2008/06/stylize-last-element-in-jquery.php">here</a>Alex Grandehttp://www.blogger.com/profile/01750789401997148077noreply@blogger.comtag:blogger.com,1999:blog-6069745790539221961.post-38975824733363212732008-06-07T22:36:00.001-07:002008-06-09T18:31:15.506-07:00AJAX Google API to Minify Javascript using Ruby on Rails<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'll explore including it from Google's <a href="http://code.google.com/apis/ajaxlibs/">AJAX Libraries API</a>.
</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'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'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" name="ruby"> javascript_include_tag("script1.js", "script2.js", "script3.js")
</pre><p><b>Result:</b>
</p>
<p style="font-family: Courier,monospace;">
<script type="text/javascript" src="/javascripts/script1.js"></script>
<script type="text/javascript" src="/javascripts/script2.js"></script>
<script type="text/javascript" src="/javascripts/script3.js"></script>
</p>
<p>There'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" name="ruby"> javascript_include_tag :all, :cache => true # when ActionController::Base.perform_caching is true</pre>
<p>The resulting code is:</p>
<p style="font-family: Courier,monospace;"><script type="text/javascript" src="/javascripts/all.js"></script></p>
<p>If you don't want them concatenated into a single file, e.g. for development purposes, you could do something like this:</p>
<pre class="code" name="ruby">
# 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:
<%= javascript_include_tag(:all, :cache => true) if DEBUG_JS == false || ENV["RAILS_ENV"] != "development"
javascript_include_tag(:all) if DEBUG_JS == true && ENV["RAILS_ENV"] == "development"
%>
</pre>
<p>I'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'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'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'll show my implementation as an example regardless.</p>
<p>I'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 (>>). 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" >> main.js
java -jar yuicompressor-2.3.5.jar "script3.js" >> main.js
java -jar yuicompressor-2.3.5.jar "script4.js" >> 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' packer). Unfortunately, I can'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, <b>you must have Java installed</b> and included in your path. If it isn't in your path, you can use the full path to Java, for instance, <span style="font-family:Courier New;">"C:\Program Files\Java\bin\java.exe" -jar [filename] [options].</span></p><h3><span style="font-family:Courier New;">Using the Google AJAX Libraries</span></h3><span style="font-family:Courier New;">
<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://code.google.com/apis/ajaxlibs/"><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer;" src="http://www.thetruetribe.com/uploaded_images/google-ajax-api-735798.png" alt="" border="0" /></a>
</span><p>Depending on your opinion about Google's recent offer to host the world'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's helpful, especially to those without access to their hosting provider'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's API, their servers are configured "correctly" 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's impossible to debug minified JavaScript (don'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'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>
<pre class="code" name="ruby">
<%=
javascript_include_tag("http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js",
:all, :cache => true) if DEBUG_JS == false || ENV["RAILS_ENV"] != "development"
javascript_include_tag("http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js",
:all) if DEBUG_JS == true && ENV["RAILS_ENV"] == "development"
%>
</pre><<p>Or, if you didn't want to include everything in the JS folder, and wanted to granularly include only specific files, you might rewrite it like so:</p><pre class="code" name="ruby">
<%= if DEBUG_JS == false || ENV["RAILS_ENV"] != "development"
javascript_include_tag ("http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js",
"main.js)
elsif DEBUG_JS == true && ENV["RAILS_ENV"] == "development"
javascript_include_tag("http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js",
"script1.js",
"script2.js",
"script3.js",
"script4.js")
end %>
</pre><p>That'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't worry about when it's in production since it will always serve up the minified, concatenated JavaScript. The logic ensures that you won'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>Jonah Dempcyhttp://www.blogger.com/profile/02468258890873289795noreply@blogger.comtag:blogger.com,1999:blog-6069745790539221961.post-35955542480521941292008-06-02T23:33:00.000-07:002008-06-03T00:07:40.640-07:00XAMPP All-in-one Web Development Stack<p style="float: left; margin-right: 8px;"><img title="XAMPP" src="http://www.apachefriends.org/images/1240.jpg" border="0" /></p><p>
It's time consuming setting up web development environments and any seasoned developer will have most likely spent <span style="font-weight:bold;">countless hours debugging</span> obscure configuration issues. Also, with the plethora of options available, some newer developers can have a hard time locating and choosing what to install.
</p><p>It turns out that most dynamic websites use a fairly common setup known as <a href="http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29">LAMP</a>, short for Linux, Apache, MySQL and PHP/Perl.</p>
<p>With this in mind, the developers at Apache Friends have released XAMPP, the X being an operating system of your choice. It comes with Apache, MySQL, PHP and Perl (along with a grab-bag of other goodies), and you can choose the package built for your OS.</p>
<p>Although I'm a sometime Ubuntu user, my current development environment is primarily on a Vista laptop. I grabbed the <a href="http://www.apachefriends.org/en/xampp-windows.html">Windows XAMPP package</a> and was amazed at how easy the "no-config" install was.</p> <p> </p><p><img title="WIZARD" src="http://www.apachefriends.org/images/1159.jpg" border="0" /></p><p>It includes:
</p><ul><li><a href="http://en.wikipedia.org/wiki/Apache_%28web_server%29">Apache</a></li><li><a href="http://en.wikipedia.org/wiki/MySQL">MySQL</a></li><li><a href="http://en.wikipedia.org/wiki/PHP">PHP</a> + <a href="http://en.wikipedia.org/wiki/PEAR">PEAR</a></li><li><a href="http://en.wikipedia.org/wiki/Perl">Perl</a></li><li><a href="http://en.wikipedia.org/wiki/OpenSSL">OpenSSL</a></li><li><a href="http://en.wikipedia.org/wiki/PhpMyAdmin">phpMyAdmin</a></li><li><a href="http://en.wikipedia.org/wiki/Webalizer">Webalizer</a></li><li>Mercury Mail Transport System</li><li>Ming</li><li>JpGraph</li><li>FileZilla FTP Server</li><li>mcrypt</li><li>eAccelerator</li><li><a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a>, and
</li><li>WEB-DAV + mod_auth_mysql.</li></ul><p>Whew! They threw in everything and the kitchen sink. But, luckily the <span style="font-weight:bold;">installation is painless </span>and you don't have to worry about the stuff you might not use, plus it's nice to know it's there if you need it. phpMyAdmin makes managing the database a breeze and above all, everything <span style="font-style: italic;">just works</span>.
</p><p>
After downloading and installing the package to C:\xampp (they recommend against placing it in Program Files on Vista due to file permissions issues), I took it for a spin by visiting http://localhost in my browser. The user is presented with a handy control panel, with links pointing to all of the various parts of the XAMPP bundle.
</p><p>
Note: I chose to run Apache and MySQL as services, meaning they will always start when the computer boots up, but you may choose to run them as standalone programs if you don't use them much. If you didn't choose to install it as a service and are not getting a response from http://localhost, make sure you're running Apache and MySQL.
You can control which parts of XAMPP are running under Start / Programs / XAMPP. This is where you can start/stop servers as well as toggle them as services.
<p><img title="CONTROLPANEL" src="http://www.apachefriends.org/images/1161.jpg" border="0" /></p><br /><i>The XAMPP control panel for start/stop Apache, MySQL, FilaZilla & Mercury</i>
</p><p>
Assuming everything is working correctly, visiting http://localhost should result in the following screen:</p>
<p><img title="xamppbrowser" src="http://www.apachefriends.org/images/1213.jpg" border="0" /></p><p>
If you need more options, such as Java/JSP support or Python, check out the add-ons available:</p>
<ul><li>Perl Addon with Mod_Perl and a selection important Perl Modules </li><li>Tomcat Addon (Requirement: SUN J2SE SDK must already be installed) </li><li>Cocoon for Tomcat Addon (Requirement: Tomcat Addon must already be installed) </li><li>Python Addon </li></ul><span style="font-style: italic;"></span>
<p>A final note: This is for <span style="font-weight:bold;">development purposes only</span>, so it has absolutely no security. Don't even think about using this set up in a live environment. You've been warned. Don't believe me? Here's the list of security holes:
</p><p>
Here a <a href="http://www.apachefriends.org/en/xampp-windows.html#644">list of missing security precautions</a> in XAMPP:
</p><p>
* The MySQL administrator (root) has no password. <br />
* The MySQL daemon is accessible via network. <br />
* PhpMyAdmin is accessible via network. <br />
* Examples are accessible via network. <br />
* The user of Mercury and FileZilla are known.
</p><p>
Even in development, it's a good idea to <span style="font-weight:bold;">set passwords</span> and disable unused services. You can do so by changing the settings at http://localhost/security in a web browser.
</p><p>
For more info on XAMPP, visit the site the FAQ:
</p><p>
<a href="http://www.apachefriends.org/en/faq-xampp-windows.html" target="_new"><img src="http://www.apachefriends.org/en/img/link.gif" border="0" /> http://www.apachefriends.org/en/faq-xampp-windows.html</a>
</p><p>
Or the forum:</p><p>
<a href="http://www.apachefriends.org/f/" target="_new"><img src="http://www.apachefriends.org/en/img/link.gif" border="0" /> http://www.apachefriends.org/f/</a>
</p>Happy XAMPPin'!Jonah Dempcyhttp://www.blogger.com/profile/02468258890873289795noreply@blogger.comtag:blogger.com,1999:blog-6069745790539221961.post-18834565776859874652008-05-31T11:24:00.000-07:002008-06-03T15:29:39.474-07:00Information Architecture Graceful Degradation Accessibility Case StudiesBased on the following website case studies, here are rules for planning graceful degradation into the architecture of a website:
<span> 1. Use forms, scrollbars, and other features that do not rely on javascript to display content.</span>
<span> 2. When content is hidden using JS-dependent components (such as tabs) figure out how to design websites to display all this content without breaking surrounding widgets and components.</span>
<span> 3. Hide javascript-dependent functionality from javascript disabled users.</span>
<span> 4. Make sure all displayed links (anchors) or buttons do something, like go to new page or scroll to specific content for users who don't have javascript.</span>
<span> 5. Build new pages that display content that otherwise would only be seen by JS users. Then you can use normal anchors to reach those pages. You can have unobstructive javascript that has event listeners on those links for sexy ajaxy functionality that users with JS can experience.</span>
<span style="font-weight: bold;font-size:130%;" >
<a href="http://www.blogger.com/">Blogger.com</a></span>
Right now I'm drafting this article in Blogger.com without javascript. A few things immediately drew my attention that are confusing or do not work. Sure I can type in a textbox; that is no surprise. Here are some things don't work:<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://www.thetruetribe.com/uploaded_images/blogger-778944.jpg"><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer;" src="http://www.thetruetribe.com/uploaded_images/blogger-778940.jpg" alt="" border="0" /></a>
1. The shortcuts (shown at the bottom) for ctrl + B for bold or ctrl + P for publish do not work at all. They should have hidden these.
2. Post Options link that is normally a drop down menu for JS users does nothing at all- a dead anchor.
<span style="font-weight: bold;">3. The top has an area called "Enclosures" with a URL input box and a MIME Type input box. I have no idea what these do.</span>
Although I can still post, many of the features that are designed for JS users still show up and should be hidden or graceful degrade to a new page showing opinions and so forth. I'm turning JS back on to finish writing this article!
<span style="font-weight: bold;font-size:130%;" >
<a href="http://www.siff.net/">Seattle International Film Festival</a>
</span>
<div style="text-align: left;">At my company <a href="http://www.pop.us/">Pop Inc</a> we care a lot about graceful degradation. We recently remade the SIFF website. I hadn't checked it out without JS before so lets take it for a spin.<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://www.thetruetribe.com/uploaded_images/siffwo-755601.jpg"><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer;" src="http://www.thetruetribe.com/uploaded_images/siffwo-755583.jpg" alt="" border="0" /></a>
</div>
<span style="font-weight: bold;">I actually liked it more with javascript disabled.</span> It loaded faster (without those JS scripts) and all the content was displayed on the page and not hidden in tabs and drop downs. I guess what to take from this website in the means of graceful degradation is designing the site ahead of time to be scalable to show all content without intruding on other components on the page.
<a href="http://www.ford.com/"><span style="font-weight: bold;font-size:130%;" >Ford</span></a>
About a year ago Ford's website displayed blank without javascript enabled. Since then they have stepped up and made a pretty nice graceful degraded homepage. <span style="font-weight: bold;">They have honed in on a great tool to display content with minimal real estate: The scroll bar.</span> While tabs, drop downs, carousels, accordions, and sliders all rely on javascript, the scrollbar works in any scenario as a way to show hidden information on the page.
Ford has taken advantage of a horizontal scrollbar to display different featured cars. Horizontal scrolling is a means that is not often utilized, but is nonetheless intriguing.
<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://www.thetruetribe.com/uploaded_images/fordwo-716348.jpg"><img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer;" src="http://www.thetruetribe.com/uploaded_images/fordwo-716316.jpg" alt="" border="0" /></a>
<a href="http://kexp.org/streamarchive/streamarchive.asp"><span style="font-size:130%;">
<span style="font-weight: bold;">KEXP</span></span></a>
KEXP is a Paul Allen/Publically owned radio station in Seattle. It is the source for indie rock music, as well as other speciality music shows. They have a pretty badass website featuring streaming archived radio shows of the past two weeks. You can listen live broadcasts anywhere in the world. <a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://www.thetruetribe.com/uploaded_images/kexp-732980.jpg"><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer;" src="http://www.thetruetribe.com/uploaded_images/kexp-732977.jpg" alt="" border="0" /></a>
Their live stream gracefully degrades as it is an anchor to a .pla file that can be opened in your favorite streaming music client. But their archived "On Demand Radio" feature is completely broken for non-javascript users. <span style="font-weight: bold;">Nothing is more maddening than to click a link or button and have nothing happen. </span>That is exactly the case for KEXP's archived radio "go" button. It relies on a javascript intrusive function. Sadly, the "go" button's A tag's hyper reference reads "javascript:selectArchive('program');".
This problem can be easily rectified by rewriting it as form with the "go"action being a input submit button. This solution works up until you reach the archive player page, the final step before listening to music. This is where a small popup comes up with a Windows Media or Real<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://www.thetruetribe.com/uploaded_images/kexpPlayer-753997.jpg"><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer;" src="http://www.thetruetribe.com/uploaded_images/kexpPlayer-753994.jpg" alt="" border="0" /></a> Audio player that allows you listen but not download the radio broadcast. There may be legal reasons why this cannot be a downloadable file. If this is the case KEXP should notify their users with some sort of message detailing why you must have javascript enabled to use the archive player.
<a href="http://www.aol.com/"><span style="font-size:130%;"><span style="font-weight: bold;">AOL</span></span></a>
<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://www.thetruetribe.com/uploaded_images/aolImage-768907.jpg"><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer;" src="http://www.thetruetribe.com/uploaded_images/aolImage-768894.jpg" alt="" border="0" /></a>
AOL did it right with their news story switcher on their homepage. With javascript allows cycling through the latest news without a page refresh. What a nice user experience! If javascript is disabled the right and left arrows on the switcher does exactly the same action except with an additional page refresh. <span style="font-weight: bold;">In other words, each news item has it's own page viewable to any user.</span>
<a href="http://www.igoogle.com/"><span style="font-weight: bold;font-size:130%;" >iGoogle</span></a>
We all know that Google's products rely heavily on javascript. Without javascript their maps will<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://www.thetruetribe.com/uploaded_images/google-738854.jpg"><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer;" src="http://www.thetruetribe.com/uploaded_images/google-738848.jpg" alt="" border="0" /></a> not display and their web browser email client won't send mail. But even simple things like the calendar and date/time widgets on iGoogle.com are completely broken and blank. <span style="font-weight: bold;">To a user who is not web savvy, this may be confusing to why the calendar is not loading while it says it is.</span> Like blogger.com's issues, Google needs to hide functionality that is javascript-dependent for javascript disabled users or inform the user why it isn't showing.Alex Grandehttp://www.blogger.com/profile/01750789401997148077noreply@blogger.comtag:blogger.com,1999:blog-6069745790539221961.post-52945712968075487762008-05-27T23:44:00.001-07:002008-05-27T23:50:52.877-07:00What is Bad About CSS Sprites?CSS Sprites have changed the way we think about website performance efficiency, but we should not be using them on every graphic and here is why:
1. <span style="font-weight: bold;">Accessibility</span> How are you going to set alt tags to background images? You can't! Screen reader users will hate you if you use background images for all your graphics just to save some seconds on page load. Being hated is bad.
2. <span style="font-weight: bold;">Printing</span> Core graphics should not be CSS Sprites because background images are not shown when printing.
In short, CSS Sprites are great for banners, rounded corners, drop shadows, certain icons, and certain buttons. But be careful how you use them. They should not be used everywhere.Alex Grandehttp://www.blogger.com/profile/01750789401997148077noreply@blogger.comtag:blogger.com,1999:blog-6069745790539221961.post-21573337276983377122008-05-25T14:41:00.000-07:002008-05-27T13:56:55.743-07:00Conducting Technical Interviews for Web Developers<p>Presumably most readers of this blog will have been through a technical interview, and I'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.</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'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'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 & 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't relevant. Once you'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'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'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'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'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't. I know I would have a hard time conducting an interview with a C++ developer, unless I had a "cheatsheet" 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'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 "in the know" 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, "the proof is in the pudding," 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't fair comparing one candidate'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'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'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't be much -- 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'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' 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'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's easy to tell:</p>
<pre name="code" class="html:nocontrols">
<!-- Sample HTML code -->
<!-- Sample HTML code -->
<p class="description" id="main">
Some text.
<span class="special">
Some more text.
</span>
</p>
</pre>
<pre name="code" 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 "special" text is <span style="font-style:italic;">orange</span>.
<h3>Hiring People who Write Good Code</h3>
<p>Besides "just working", the criteria for what makes good code differs from person to person, but in general, you'll want to look for readability, useful comments, simplicity, accuracy, good formatting and code that doesn'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>Jonah Dempcyhttp://www.blogger.com/profile/02468258890873289795noreply@blogger.comtag:blogger.com,1999:blog-6069745790539221961.post-41404257073718825402008-05-20T17:24:00.000-07:002008-05-21T12:41:05.872-07:00Inspecting Javascript with Firebug1. Go to <a href="http://www.alexgrande.com/breakable/">http://www.alexgrande.com/breakable/</a> and add the link to your bookmarks.
<br />
<img src="http://www.alexgrande.com/breakable/01.jpg" />
<br /><br />
2. Go to the page you are interested in inspecting and click on the bookmark in your browser called "Inspect JS". That will load breakable.js into the head of the page you are currently using.
<br />
<img src="http://www.alexgrande.com/breakable/02.jpg" />
<br /><br />
3. In firebug go into the scripts tab and view breakable.js.
<br />
4. Set a break point on line 7 where it says funct();
<br />
<img src="http://www.alexgrande.com/breakable/03.jpg" />
<br /><br />
5. Find out what the ID is of the element that has the event listener.
<br />
<img src="http://www.alexgrande.com/breakable/04.jpg" />
<br /><br />
6. Click the console tab in firebug. Type in: breakOn("elementID", "eventTrigger");
Example: breakOn("prettyImageOver", "onmouseover"); Example 2: breakOn("ajaxImageChanger","onclick");
<br />
<img src="http://www.alexgrande.com/breakable/05.jpg" />
<br /><br />
7. (1)Initialize the event by mousing over it or whatever you you chose as the event trigger. If the original js author chose a mouse over event then you should also use a mouse over event. Because if you choose an onclick for an onmouseover event then by the time you click it the event has already passed you by..
<br />
8. (2)Firebug will transfer over to the breakable.js in the scripts tab at the breakpoint funct(). Step into it by (3)clicking the arrow right in firebug script section.
<br />
<img src="http://www.alexgrande.com/breakable/06.jpg" />
<br /><br />
9. and you will enter into the javascript code of whatever function is called by the event.
<br />
<img src="http://www.alexgrande.com/breakable/07.jpg" />
<br /><br />
I love this! Big thanks to my friend Grady Morgan for writing this short script!Alex Grandehttp://www.blogger.com/profile/01750789401997148077noreply@blogger.comtag:blogger.com,1999:blog-6069745790539221961.post-77860184021219928422008-05-17T14:58:00.000-07:002008-05-20T15:55:58.775-07:00The Group Class in MooTools<p>The MooTools Group class is for grouping a collection of objects and calling a function when all of those objects have fired a particular event. For instance, you could group an array of Element objects and fire an event when all of them have been clicked. Or, you could group a collection of Ajax request objects and fire an event when all have completed. (Both of these examples are straight from the <a href="http://docs12b.mootools.net/Plugins/Group">MooTools 1.2 Beta docs for Plugins/Group</a>).</p>
<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://docs12b.mootools.net/Plugins/Group"><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer;" src="http://www.thetruetribe.com/uploaded_images/mootools-group-class-720828.jpg" alt="" border="0" /></a>
<p>How is this useful? Well, it's a convenience for when events depend on each others' completion but occur asynchronously, either by Ajax or through use of timers. Let's look at an example of how to handle dependent events without grouping first, to see where there is room for improvement:</p>
<pre name="code" class="js">
// Flags to keep track of the request status
var firstRequestIsComplete = false;
var secondRequestIsComplete = false;
window.addEvent('domready', function() {
var firstRequest = new Request({
url: 'example-1.html',
onSuccess: function() {
firstRequestIsComplete = true;
if (secondRequestIsComplete) {
console.log('Both requests are complete.');
}
}
}).send(); // Fire it
var secondRequest = new Request({
url: 'example-1.html',
onSuccess: function() {
secondRequestIsComplete = true;
if (firstRequestIsComplete) {
console.log('Both requests are complete.');
}
}
}).send(); // Fire it
});
</pre>
<p>Obviously, this isn't a stellar solution. Having to keep track of which Ajax requests have already fired using flags is a hassle, and this example only uses two requests. Say you had 10 different requests and you wanted to fire an event once all of them had completed. You'd need to <b>store flags for which request had fired</b> and which hadn't, perhaps in a hash table, and write a function that checks if all of the requests had fired or not. Then, for the <i>onSuccess</i> event handler of each request, you'd need to set a condition that calls the function to check if all had succeeded, and performs your desired action if so (in the above example, logging to the console).</p>
<p>What a hassle! All of this checking and logic duplicated in each request; there must be a better way.</p>
<h3>Grouping Ajax Requests in MooTools</h3>
<div style="float: right; font-size: 10px; width: 166px; margin-left: 18px; margin-bottom: 4px;"> <span class="photo_container pc_m"><a href="http://www.flickr.com/photos/nickwheeleroz/2166114756/" title="Ajax"><img src="http://farm3.static.flickr.com/2069/2166114756_1358c1a1f4_m.jpg" alt="Ajax" class="pc_img" height="240" width="166" /></a> Ajax by <a href="http://www.flickr.com/photos/nickwheeleroz/">nickwheeleroz</a> </span> </div><p>As it turns out, <b>there is a better way</b>, thanks to MooTools. Let's see how this code is cleaned up by the use of grouping with MooTools' Group class:</p>
<pre name="code" class="js">
window.addEvent('domready', function() {
var firstRequest = new Request({url: 'example-1.html'});
var secondRequest = new Request({url: 'example-1.html'});
var ajaxRequests = new Group(firstRequest, secondRequest);
ajaxRequests.addEvent('onSuccess', function() {
console.log('Both requests are complete.');
});
// Fire requests
firstRequest.send();
secondRequest.send();
});
</pre>
<p>All right! Now we've removed the duplicate logging code and <i>onSuccess</i> events, which were previously declared in two places. This code has the exact same effect as the previous implementation, but we're following the "write once" principle.</p>
<p>You could make it <b>even more concise using chaining</b>, if that's your thing:
</p><pre name="code" class="js">
window.addEvent('domready', function() {
new Group(new Request({url: 'example-1.html'}),
new Request({url: 'example-1.html'}))
.addEvent('onSuccess', function() {
console.log('Both requests are complete.');
}).instances.each(function(instance) {
instance.send();
});
});
</pre>
<p>To me, the chaining isn't necessary here and iterating over the instances array stored in the group object probably isn't the best idea, since it's exposing the inner workings of the class by direct reference, rather than through the API. So, this example is only shown for the purposes of demonstrating how you can chain functions with MooTools, if you so desire.</p>
<h3>Caveats and Gotchas with MooTools Groups</h3>
<p>
There are a few crucial gotchas that will hang you up if you aren't aware of them. First, the API documentation for MooTools 1.2beta is not accurate. It may be accurate for 1.1, but it certainly isn't for 1.2. They show an example of grouping using the Ajax class which was renamed Request in MooTools 1.2. The docs call the <i>request()</i> method to initiate an Ajax request but in actuality, it is the <i>send()</i> method. Can you spot any other inaccuracies in the example provided by the docs?</p>
<pre name="code" class="js:nocontrols">
// From http://docs12b.mootools.net/Plugins/Group
//
// NOTE: This code will not work for MooTools 1.2.
// Shown for educational purposes only.
var xhr1 = new Ajax('data.js', {evalScript: true});
var xhr2 = new Ajax('abstraction.js', {evalScript: true});
var xhr3 = new Ajax('template.js', {evalScript: true});
var group = new Group(xhr1, xhr2, xhr3);
group.addEvent('complete', function(){
alert('All Scripts loaded');
});
xhr1.request();
xhr2.request();
xhr3.request();
</pre>
<p>
A few other problems with the example: It shows the <i>onComplete</i> event instead of <i>onSuccess</i>, and the arguments passed to the Ajax constructor are incorrect as well. Finally, it shows the event to monitor without the 'on-' prefix. Given the plethora of inaccuracies in the docs, I believe these nuances warrant further discussion. Let's look at each of these in turn.</p>
<p>The <b>Ajax class was renamed to Request </b>in MooTools 1.2 and the API was significantly overhauled. Instead of calling <i>request()</i> to initiate the request, now you must <i>send()</i> it. Now, the constructor takes an <i>options</i> object which has properties for all of the arguments, such as <i>url</i>. In the example given, the URL is passed as the first argument, but in the current code you provide it as a property of the options object instead:
</p>
<pre name="code" class="js:nocontrols">
// This code demonstrates the differences in how to make
// Ajax requests between MooTools 1.1 and MooTools 1.2:
// Old way
new Ajax('path/to/your/data', {
// options go here
}).request(); // fire the request
// New way
new Request({
url: 'path/to/your/data'
// options go here
}).send(); // fire the request
</pre>
<p>
As you can see, the URL is passed in via a property of the <i>options</i> object, rather than as the first argument of the constructor. I prefer this, as the MooTools API has been made much more consistent in 1.2 with most classes simply taking an <i>options</i> object, rather than a variety of parameters.</p>
<p>Another problem with the example provided in the docs is that it shows the <i>onComplete</i> event when this has been changed to <i>onSuccess</i>. And, to make matters worse, the docs exclude the 'on-' prefix in their example. Compare the right and wrong ways to monitor group events in MooTools 1.2:</p>
<pre name="code" class="javascript:nocontrols">
// Wrong way (as shown in docs)
group.addEvent('complete', function(){
alert('All Scripts loaded');
});
// Right way
group.addEvent('onSuccess', function(){
alert('All Scripts loaded');
});
</pre>
<p>This is kind of odd, I'll admit, and inconsistent with the <i>addEvent()</i> API. Usually, you register events without the 'on-' prefix. But, for some reason, when you monitor an event in the group, <b>you must use the 'on-' prefix</b>. I discovered this after 20 minutes fruitlessly searching the web and stepping through my code, so hopefully this gem of information will save others that same trouble.</p>
<h3>Testing MooTools Ajax Locally</h3>
<p>Something crucial to be aware of when testing these examples is that
you <b>must serve the response to the Ajax request from a web server.</b> If you access the page through the file:// protocol instead of http:// protocol, certain headers will not be present and MooTools won't fire the <i>onSuccess</i> event.</p>
<p>There's actually a funny story about this: At my old job, there was a contest to build an Ajax widget using various JavaScript frameworks. The MooTools team got hung up because they were testing through the file:// protocol (without a web server, just by opening the file directly with a web browser) and the Ajax requests were never firing their <i>onComplete</i> event handlers (this was back in MooTools 1.1 where it was called <i>onComplete</i> instead of <i>onSuccess</i>). Well, what's funny about it is that the Ajax request would fire <i>onFailure</i>, but it called the event handler with the Ajax response! The team building the widget actually got it working fine but it was "failing" every time-- the Ajax callback function was registered to the <i>onFailure</i> event.</p>
<p>So, the moral of the story is, try to avoid hacky workaround like this and serve up the Ajax responses <b>the right way, through a web server</b>.</p>
<p>Besides Ajax, what are some other uses of groups you can think of? Post your ideas in the comments and they may become the basis of future articles.</p>Jonah Dempcyhttp://www.blogger.com/profile/02468258890873289795noreply@blogger.comtag:blogger.com,1999:blog-6069745790539221961.post-22466595144315972562008-05-16T14:06:00.000-07:002008-05-16T21:11:44.508-07:00MooTools mouseenter and mouseleave Events For Dropdowns<p>One of the frustrations many coders have encountered when creating JavaScript flyout menus is the fact that <span style="font-style:italic;">onmouseover</span> and <span style="font-style:italic;">onmouseout</span> events <span style="font-weight:bold;">fire when entering children elements</span>. This is usually not the desired effect when creating popup, dropdown or flyout menus.</p>
<img style="float: right; margin-left: 18px; margin-bottom: 4px;" src="http://docs12b.mootools.net/assets/images/mootools.png" alt="MooTools" />
<p>MooTools offers its own <span style="font-style:italic;">mouseenter</span> and <span style="font-style:italic;">mouseleave</span> events which alleviate the problem of the events firing when entering child elements, but before diving into that, let's explore why it's such a problem in the first place.</p>
<p>At first thought, it would seem that you want <span style="font-style:italic;">onmouseout </span>to fire when leaving the element, right? Well, generally that's only the case when you're mousing off a flyout menu, for instance. But when you're staying inside the flyout menu and mousing over one of the child elements, you don't want the <span style="font-style:italic;">onmouseout</span> event to fire, since it will have an event handler registered to close the flyout.</p>
Take, for example, this simple flyout menu. Shown here is the barebones HTML for the menu:
<pre name="code" class="html:nocontrols">
<ul class="flyout-main">
<li>Level 1
<ul class="flyout-sub">
<li>Level 2</li>
<li>Level 2</li>
<li>Level 2</li>
</ul>
</li>
<li>Level 1
<ul class="flyout-sub">
<li>Level 2</li>
</ul>
</li>
<li>Level 1
<ul class="flyout-sub">
<li>Level 2</li>
<li>Level 2</li>
</ul>
</li>
</ul>
</pre>
<p>This results in a list with 3 top-level headings, each containing 1-3 sub headings. Each sub-heading is represented as a <span style="font-style:italic;">ul</span> element with class <span style="font-style:italic;">flyout-sub</span>, and will be hidden using CSS and only visible when the user mouses over its respective top level heading. Here's the CSS:</p>
<pre name="code" class="css:nocontrols">
ul.flyout-sub {
display: none;
}
li.active ul.flyout-sub {
display: block;
}
</pre>
<p>Pretty simple stuff. We just hide the second level by default and show it if it has a parent <span style="font-style:italic;">li</span> with class <span style="font-style:italic;">active</span>. So, <span style="font-weight:bold;">it's up to the JavaScript</span> to toggle the <span style="font-style:italic;">active</span> class.
<p>Here is the JavaScript. Note the use of oldschool JavaScript event registration using the core DOM events <span style="font-style:italic;">onmouseover</span> and <span style="font-style:italic;">onmouseout</span>.</p>
<pre name="code" class="js:nocontrols">
window.addEvent('domready', function() {
$$('ul.flyout-main > li').each(function(li) {
li.onmouseover = function() {
li.addClass('active');
}
li.onmouseout = function() {
li.removeClass('active');
}
});
});
</pre>
<p>If you test this code, you'll see that it doesn't have the desired effect: The <span style="font-style:italic;">onmouseover</span> and <span style="font-style:italic;">onmouseout</span> events fire when entering child elements so you're unable to mouse over the sub menu without closing it. A simple change to MooTools <span style="font-style:italic;">mouseenter</span> and <span style="font-style:italic;">mouseleave</span> events (which only fire when entering/exiting from the parent) solves this problem nicely:</p>
<pre name="code" class="js:nocontrols">
window.addEvent('domready', function() {
$$('ul.flyout-main > li').each(function(li) {
li.addEvent('mouseenter', function() {
li.addClass('active');
});
li.addEvent('mouseleave', function() {
li.removeClass('active');
});
});
});
</pre>
<p>Before I knew about MooTools' <span style="font-style:italic;">mouseenter</span> and <span style="font-style:italic;">mouseleave</span> events, I devised a few workarounds to this using <span style="font-style:italic;">onmouseover</span> and <span style="font-style:italic;">onmouseout</span>. One such solution was to have the event handler function check to see if the <span style="font-style:italic;">targetElement</span> of the event object was a child of the flyout menu. But, whichever solution I devised, it was sub-optimal and involved additional logic for something that should be free in a programming language. Now, thanks to MooTools, it is-- providing you include the MooTools library, of course.</p>
<p>Armed with this knowledge of how <span style="font-style:italic;">mouseenter</span> and <span style="font-style:italic;">mouseleave</span> differ from the conventional <span style="font-style:italic;">onmouseout</span> and <span style="font-style:italic;">onmouseover</span> events, you now have another powerful time-saving tool for making dynamic web interfaces. Instead of mitigating annoying issues with the limited set of core JavaScript events, you can focus on what you want the code to do, not how you want to do it.</p>
<p>For more information, visit the <a href="http://docs12b.mootools.net/Element/Element.Event#">MooTools 1.2 beta docs for Element.Event</a>.</p>Jonah Dempcyhttp://www.blogger.com/profile/02468258890873289795noreply@blogger.comtag:blogger.com,1999:blog-6069745790539221961.post-74813356084018888972008-05-14T02:27:00.000-07:002008-05-15T17:25:43.302-07:00JavaScript Challenge: Reverse a Linked List<p>This article is a follow-up on my previous post on <a href="http://www.thetruetribe.com/2008/05/linkedlist-class-in-mootools.html">writing a linked list class in MooTools</a>. In that post, I offered an implementation of a singly-linked list in JavaScript and gave a challenge: To reverse a linked list in place, starting with only a reference to the head. The challenge also forbade the use of storing the data externally -- that is to say, you can't just iterate over the linked list and stuff the items in a new array, then reverse the array.</p>
<p>As promised, <span style="font-weight:bold;">here is my solution</span> to the challenge. If you are planning on trying the challenge yourself, read no further.</p>
<p>I've included the code for defining the LinkedList and LinkedListItem classes as well. It's separate from my solution, so if you want to give it a try yourself, go ahead and copy the code below.</p>
<pre name="code" 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 > 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;
}
});
// 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>For an in-depth discussion of this code including step-by-step commentary, check out the previous article, <a href="http://www.thetruetribe.com/2008/05/linkedlist-class-in-mootools.html">LinkedList Class in MooTools</a>.
<h3>Reverse a Linked List: Solution</h3>
<p>This is what I came up with:</p>
<pre name="code" class="js">
window.addEvent('domready', function() {
var list = new LinkedList(['a', 'b', 'c', 'd', 'e',
'f', 'g', '1', '2', '3',
'4', '5']);
// Challenge: Reverse the linked list in place (list.collection)
// without using another array
// Input: LinkedList list
function reverseLinkedList(list) {
// Inputs: LinkedListItem item, LinkedListItem next
//
// Returns true if next item exists
// If not, sets the head to be the existing item
function checkForNextItem(item, next) {
if (!$defined(next)) {
list.setFirst(item);
return false;
} else {
return true;
}
}
// Our new tail is the old head
var tail = list.getFirst(); // 0
var itemOne = tail.getNext(); // 1
// If there is only one element in the list, return it
if (!$defined(itemOne)) {
return list;
}
// Remove the old link from the tail
tail.setNext(null);
// Prepare third item variable for while() loop
var itemThree = tail;
// The while() loop will stop when the checkForNextItem()
// function fails to find a next item and calls
// list.setFirst() on the final existing item.
while (list.getFirst() == tail) {
itemTwo = itemOne.getNext(); // 2
itemOne.setNext(itemThree); // link 1 to 0
if (!checkForNextItem(itemOne, itemTwo)) break;
itemThree = itemTwo.getNext(); // 3
itemTwo.setNext(itemOne); // link 2 to 1
if (!checkForNextItem(itemTwo, itemThree)) break;
itemOne = itemThree.getNext(); // 4
itemThree.setNext(itemTwo); // link 3 to 2
checkForNextItem(itemThree, itemOne);
}
return list.getAll();
}
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>The main part of the function that does the work of reversing the linked list is the <span style="font-style:italic;">while()</span> loop. I use a helper method, <span style="font-style:italic;">checkForNextItem()</span>, which is declared at the top.</p><p>You'll notice I declared the function inside the <span style="font-style:italic;">reverseLinkedList()</span> function. The reason I did this is that <span style="font-style:italic;">checkForNextItem()</span> is a private method that shouldn't be accessible to code outside of the scope of the <span style="font-style:italic;">reverseLinkedList()</span> function. Just like declaring local variables when you don't need a global, you can declare private methods inside the scope of the function block. It's perfect for helper methods like this and it doesn't clutter the global namespace.</p>
<p>To explain what the <span style="font-style:italic;">checkForNextItem()</span> actually does, let's examine the <span style="font-style:italic;">while()</span> loop where it's used.</p>
<pre name="code" class="js:nocontrols">
while (list.getFirst() == tail) {
itemTwo = itemOne.getNext();
itemOne.setNext(itemThree);
if (!checkForNextItem(itemOne, itemTwo)) break;
itemThree = itemTwo.getNext();
itemTwo.setNext(itemOne);
if (!checkForNextItem(itemTwo, itemThree)) break;
itemOne = itemThree.getNext();
itemThree.setNext(itemTwo);
checkForNextItem(itemThree, itemOne);
}
</pre>
<p>The <span style="font-style:italic;">while()</span> loop continues until list.getFirst() no longer returns the tail (the old head). At that point, the loop knows to finish because the <span style="font-style:italic;">checkForNextItem()</span> method, unable to find a next item, will set the head to be the final remaining item in the list. Thus, the old tail becomes the new head and the linked list is reversed.</p>
<p>The only other area of the code which warrants discussion is the check if there is only one item in the list, and calling <span style="font-style:italic;">setNext(null)</span> on the new tail (the former head):</p>
<pre name="code" class="js:nocontrols">
// Our new tail is the old head
var tail = list.getFirst(); // 0
var itemOne = tail.getNext(); // 1
// If there is only one element in the list, return it
if (!$defined(itemOne)) {
return list;
}
// Remove the old link from the tail
tail.setNext(null);
</pre>
<p>The check to make sure itemOne is defined is simply a fail-safe for linked lists with only one item. In that case, <span style="font-style:italic;">tail.getNext()</span> will be undefined so we just return the list as it is, with only one item. Originally I wrote the check using the JavaScript <span style="font-style:italic;">typeof</span> keyword (i.e. <span style=