Unobtrusive Observer
Walter Davis
13 Nov, 2009
An unobtrusive observer is a design pattern for JavaScript that epitomizes the idea of “progressive enhancement”. Instead of littering your page layout with inline scripts, you set an observer in the head of the page, where non-scripted browsers can safely ignore it.
Progressive enhancement is a principle of user-interface design which states that anyone who visits your page should have good basic functional experience, regardless of their browser or preferences. Anything extra, like fancy effects, should be layered over that core functionality in a manner that degrades gracefully. Nothing that the visitor must do should be hidden behind a nice-to-have graphical effect.
Let’s imagine that you have built an Accordion effect, where all but one of the elements are meant to be hidden at the initial page view. If you followed the usual means of setting this up — setting display:none; on the hidden elements within your page code — there would be some visitors (those with JavaScript disabled for some reason) who would not see that hidden content at all. You might also be marked down on search engines that look for this technique as a way to cheat.
A nicer way to do this would be to hide those elements as soon as the DOM is loaded, but before the page actually displays in the browser. We’ll use the Protaculous Action to set this up.
- Apply the Protaculous Action to the page, and select prototype-packed from the Library selector.
- Click on the first Function Body button to open the
dom:loadedevent handler. - In the code box, enter the following…
Code:
$$('div#yourAccordion div').invoke('hide');
$('yourAccordion').down('div').show();
Now, when a visitor comes to your page, the first thing they see will be a closed-up Accordion with the first option showing. And if a visitor without JavaScript comes to your page, they will see the entire array of options completely opened up. Nobody loses out.
So how does this work? The event we are observing is the dom:loaded event, which is fired by the browser when it has completely downloaded everything it needs to calculate the layout of the page, but not necessarily all of the resources needed to display it.
The Protaculous Action writes the following code into the head of your page:
<script type="text/javascript">
document.observe('dom:loaded',function(){
$$('#yourAccordion div').invoke('hide');
$('yourAccordion').down('div').show();
});
</script>
Down in the body of your page, there is no scripting going on, simply regular Freeway layout code. The connection between the observer and the layout is the ID of the parent container of your Accordion. All of the behavior (hiding) is done using this progressive enhancement, so it only happens for the visitors who can appreciate it.
