Clean source with jQuery

Writing Javascript just isn’t fun. The language doesn’t come with much out-of-the-box and the road to even the simplest task is paved with cross-browser quirks, gotchas, and caveats. Open-source libraries like jQuery, Prototype, and Mootools seek to address this by extending Javascript with robust DOM scripting while saving you from worrying about browser compatibility.

We’d talked about these frameworks internally as part of a larger question — where does third-party open-source software fit in our work? — but hadn’t had the chance to play with one in a real way until we dove into development of an as-yet-unannounced project that nicely straddles the line between client work and internal development. We opted for jQuery (I like it philosophically), but all three of the major libraries offer very similar functionality.

It’s been a game-changing experience. Our Javascript workflow could not be any more different. I could go on here for pages about being able to use CSS selectors to grab DOM elements ($('li a.new').fadeIn() automatically slow fades all class="new" links that appear in a list item) or how I’ve been able to reduce dozens of lines of code to two or three. But the single best change is the whistle-clean source.

It happened with CSS years ago. Separation of presentation and content is at the very base level of any standards-based web design, but the sister goal of doing the same with Javascript has hovered just outside of practicality. Attaching and properly handling events outside of inline on* event attributes is a lofty but near unattainable goal when starting from scratch (ask anyone who has peered into the abyss of event bubbling).

With jQuery, though, it’s as simple as $('h3 a').click(doSomething) and the onclick function is attached transparently at page load. And you can get quite fancy. We recently ran into a case, for instance, where we were showing a series of icons and CSS-styled buttons for each item returned from a database. In previous projects, the PHP web application would deliver the XHTML tags directly; with jQuery, all the webapp has to handle is returning the semantic text. jQuery swoops in and gussies it up on page load. If we need to change something it’s just as easy as changing a style declaration. No need to even think about the XHTML document: literally 100% of your Javascript code exists in your .js file.

When we start coding a new page, then, we no longer have to think about Javascript versus non-Javascript functionality. We are free to design how we like, and every bit of functionality works without Javascript because there is no Javascript in the source. And then when things are bulletproof, we add all the pizzaz we want.

— Donald