Unobtrusive Javascript
For a long time I hated Javascript. If you started web programming in the 90’s, you know what I mean. Browser support was spotty at best. Even later when AJAX hit the scene, I resisted vehemently.
It took me a long time to come around, but now with libraries like prototype, jQuery, and MooTools, Javascript is my friend again. Now you don’t have to rely on icky things like Flash to accomplish some pretty amazing feats. Chrome Experiments will blow your mind (intended to be viewed in Google’s Chrome Browser, but Safari 4 is fine, and Firefox does ok).
The push has always been for standards: sites that degrade gracefully. If you don’t have Flash, you can’t view a Flash-based site (same goes for Silverlight). But, if the web developer has done her job, anyone who doesn’t have Javascript-enabled should still have a decent experience navigating your content.
The Old Way
Generally the technique was to put your Javascript in the onlick attribute of anchor tags or the onchange attribute of text inputs. Like having font tags littering your HTML, this left your markup looking like a jumbled mess, and it was very difficult to change behavior in a uniform way.
<a href=”http://google.com” onclick=”alert(’Big Brother is Google!!!’);”>Go to Big Brother</a>
The New Way
There is a better way. You can keep all that Javascript out of your markup completely using bindings. For instance in jQuery I can write this:
$(”a”).bind(”click”, function() { alert(’You have been warned’); });
Put this in a .js file or in the head of your markup, and be done with mixing function and markup (the same way you should be done with mixing style and markup).
Rails 3 Support for Unobtrusive Javascript
While this technique is eloquent and powerful, it is somewhat difficult to abstract away using frameworks such as Rails, so until Rails 3 it was left to the developer to implement it. This left the developer in a predicament, because the ease of development using standard Rails AJAX (via prototype) methods would have to be sacrificed to obtain truly clean markup. Rails 3 has found a way to take the best of both worlds, using HTML 5 attributes and binding. Whether this will degrade gracefully or not is still in question, but it is exciting nonetheless. Check out the other features coming by watching the core team at RailsConf.
