<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ryan Morr &#187; Articles</title>
	<atom:link href="http://ryanmorr.com/archives/category/articles/feed" rel="self" type="application/rss+xml" />
	<link>http://ryanmorr.com</link>
	<description>JavaScript, CSS, and Web Apps</description>
	<lastBuildDate>Fri, 27 Aug 2010 13:28:41 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Leveraging the Most out of CSS Classes</title>
		<link>http://ryanmorr.com/archives/leveraging-the-most-out-of-css-classes</link>
		<comments>http://ryanmorr.com/archives/leveraging-the-most-out-of-css-classes#comments</comments>
		<pubDate>Fri, 27 Aug 2010 03:06:44 +0000</pubDate>
		<dc:creator>Ryan Morr</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[XHTML]]></category>
		<category><![CDATA[DOM]]></category>

		<guid isPermaLink="false">http://ryanmorr.com/?p=1807</guid>
		<description><![CDATA[To harness or exploit the most out of CSS classes is to take advantage of what truly is the unsung hero of advanced RIA development as it relates to the presentation layer. When we observe our markup, we find that various portions of the DOM may require styling influences on the initial page load as [...]]]></description>
			<content:encoded><![CDATA[<p>To harness or exploit the most out of CSS classes is to take advantage of what truly is the unsung hero of advanced RIA development as it relates to the presentation layer. When we observe our markup, we find that various portions of the DOM may require styling influences on the initial page load as well as interaction events or cues to adjust its structure, positioning, visibility, state, and skin. For this classes are the clear suitor, as it brings flexibility, modularity, inheritance, and a dynamic and unobtrusive nature to the table.<span id="more-1807"></span></p>
<h3>Benefits</h3>
<p>One benefit in particular is in a nodes ability to support multiple class declarations at a time, which in a sense facilitates a multiple inheritance of sorts. This gives us the unique ability within CSS to separate an element&#8217;s various states and differing characteristics to create a more modular approach in our stylesheets. By doing so, we can create classes that are in no way specific to any one element but merely represents a characteristic or group of characteristics that any node can adopt provided the class name.</p>
<p>Inheritance can also play a key role in the design process, by letting the cascade flow through the DOM we can leverage the styles of ancestor nodes and avoid a rigid implementation with redundant style declarations. If we employ this technique, we can easily alter state of descendant nodes by adding or removing a class to or from that of an ancestor node while avoiding the need to traverse the DOM to manipulate each descendant node individually in our script.</p>
<p>As far as client-side scripting is concerned, classes are the preferred window to CSS from JavaScript. By hiding styling characteristics behind class names, JavaScript can merely alter a node&#8217;s <em>className</em> attribute to activate or deactivate a specific state of that node. In this case, JavaScript is not concerned with what styling influences are taking place on page load or even after event triggered changes in state. This allows  us to quickly consult our CSS to make minor styling changes rather than JavaScript.</p>
<h3>Abstract Classes</h3>
<p>Abstract classes are those that do not necessarily reflect a state or any specific node but common characteristics shared between nodes of varying purpose and context. Take for instance the following:</p>

<div class="wp_syntax"><div class="code"><pre class="css" style="font-family:monospace;"><span style="color: #6666ff;">.widget</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">font-family</span><span style="color: #00AA00;">:</span> Trebuchet MS<span style="color: #00AA00;">,</span> Tahoma<span style="color: #00AA00;">,</span> Verdana<span style="color: #00AA00;">,</span> Arial<span style="color: #00AA00;">,</span> <span style="color: #993333;">sans-serif</span><span style="color: #00AA00;">;</span>
    <span style="color: #000000; font-weight: bold;">font-size</span><span style="color: #00AA00;">:</span> <span style="color: #933;">1.1em</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.overlay</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">position</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">absolute</span><span style="color: #00AA00;">;</span>
    <span style="color: #000000; font-weight: bold;">top</span><span style="color: #00AA00;">:</span> <span style="color: #cc66cc;">0</span><span style="color: #00AA00;">;</span>
    <span style="color: #000000; font-weight: bold;">left</span><span style="color: #00AA00;">:</span> <span style="color: #cc66cc;">0</span><span style="color: #00AA00;">;</span>
    <span style="color: #000000; font-weight: bold;">width</span><span style="color: #00AA00;">:</span> <span style="color: #933;"><span style="color: #cc66cc;">100</span>%</span><span style="color: #00AA00;">;</span>
    <span style="color: #000000; font-weight: bold;">height</span><span style="color: #00AA00;">:</span> <span style="color: #933;"><span style="color: #cc66cc;">100</span>%</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.content</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">display</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">block</span><span style="color: #00AA00;">;</span>
    -khtml-box-sizing<span style="color: #00AA00;">:</span> content-box<span style="color: #00AA00;">;</span>
    -webkit-box-sizing<span style="color: #00AA00;">:</span> content-box<span style="color: #00AA00;">;</span>
    -moz-box-sizing<span style="color: #00AA00;">:</span> content-box<span style="color: #00AA00;">;</span>
    -ms-box-sizing<span style="color: #00AA00;">:</span> content-box<span style="color: #00AA00;">;</span>
    -o-box-sizing<span style="color: #00AA00;">:</span> content-box<span style="color: #00AA00;">;</span>
    box-sizing<span style="color: #00AA00;">:</span> content-box<span style="color: #00AA00;">;</span>
    zoom<span style="color: #00AA00;">:</span> <span style="color: #cc66cc;">1</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span></pre></div></div>

<p>As you can see these examples are of a very generic nature both in name and styling influences as they represent a very high level abstraction. Typically classes such as these should always be combined with others as part of a node&#8217;s class declaration to round out its structure, positioning, state, and skin.</p>
<p>The advantage of abstract classes do not come solely in their ability to apply styles to a node in a modular fashion, but also in the relationships they create. Think of it from the perspective of object-oriented programming, provided the overlay class, a node will inherit the role of an overlay. For example:</p>

<div class="wp_syntax"><div class="code"><pre class="html4strict" style="font-family:monospace;"><span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;widget&quot;</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;overlay widget&quot;</span>&gt;</span>
        <span style="color: #808080; font-style: italic;">&lt;!-- widget markup --&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span></pre></div></div>

<p>In this case, the parent node <em>is a</em> widget and <em>has a</em> widget and <em>has a</em> overlay while the child node <em>is a</em> widget and <em>is a</em> overlay. Although the child node is both an overlay and a widget, it is important to recognize that this node can be referenced by either statement together or independently of the other, like so:</p>

<div class="wp_syntax"><div class="code"><pre class="css" style="font-family:monospace;"><span style="color: #6666ff;">.widget</span> <span style="color: #6666ff;">.overlay</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #808080; font-style: italic;">/* target overlays that belong to widgets */</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.widget</span> <span style="color: #6666ff;">.widget</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #808080; font-style: italic;">/* target widgets that belong to widgets */</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.widget</span> <span style="color: #6666ff;">.widget</span><span style="color: #6666ff;">.overlay</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #808080; font-style: italic;">/* target overlays that are also widgets that belong to widgets */</span>
<span style="color: #00AA00;">&#125;</span></pre></div></div>

<p>By grouping nodes together in this manner we can target nodes based on their role, state, structure, positioning, document position, or relativity to other nodes. From here we let inheritance fill in the gaps; as we move further down the DOM hierarchy the more precise and relevant our styles become to the specific nodes to which they are applied. Width and height, for example, should typically be reserved for styling in a low level context, while font (family, size, and color) is best served at a high level. Not to mention that this grouping makes it very easy for JavaScript to quickly reference or query for various nodes in various contexts for fast and easy manipulation.</p>
<h3>Character Classes</h3>
<p>Similar to abstract classes, character classes work on a lower level context and are designed to fulfil one purpose relating to a characteristic or group of characteristics. They help to achieve both visual and cross-browser consistency across an application in the purpose that they serve. For example, the following are some character classes of varying purposes:</p>

<div class="wp_syntax"><div class="code"><pre class="css" style="font-family:monospace;"><span style="color: #6666ff;">.hidden</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">display</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">none</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.float-left</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">float</span><span style="color: #00AA00;">:</span> <span style="color: #000000; font-weight: bold;">left</span><span style="color: #00AA00;">;</span>
    <span style="color: #000000; font-weight: bold;">display</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">inline</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.center</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">margin-left</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">auto</span><span style="color: #00AA00;">;</span>
    <span style="color: #000000; font-weight: bold;">margin-right</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">auto</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.text-overflow</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">width</span><span style="color: #00AA00;">:</span> <span style="color: #933;"><span style="color: #cc66cc;">100</span>%</span><span style="color: #00AA00;">;</span>
    text-<span style="color: #000000; font-weight: bold;">overflow</span><span style="color: #00AA00;">:</span> ellipsis<span style="color: #00AA00;">;</span>
    -o-text-<span style="color: #000000; font-weight: bold;">overflow</span><span style="color: #00AA00;">:</span> ellipsis<span style="color: #00AA00;">;</span>
    <span style="color: #000000; font-weight: bold;">white-space</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">nowrap</span><span style="color: #00AA00;">;</span>
    <span style="color: #000000; font-weight: bold;">overflow</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">hidden</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span></pre></div></div>

<p>Typically character classes do not need to be overridden in a lower level context as they should be mutually exclusive from your structure and skin. You&#8217;ll also want to avoid depending on character classes to target descendants as part of a selector statement. Doing so will expand the scope of the class beyond its original purpose, this can snow ball into further dependencies that result in a loss of modularity and flexibility. </p>
<p>Exploiting character classes to the fullest means easy adoption of shared markup conventions and allow for ease in code integration. By putting together a small component library, you will find that they will not only provide reusable classes throughout an entire application but also amongst projects.</p>
<h3>Themed Classes</h3>
<p>As you might have guessed, themed classes have everything to do with your skin, this means fonts, colors, background images, formatting, icons, and states. Take for instance the following:</p>

<div class="wp_syntax"><div class="code"><pre class="css" style="font-family:monospace;"><span style="color: #6666ff;">.loading</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">cursor</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">wait</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.active</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">border</span><span style="color: #00AA00;">:</span> <span style="color: #933;">1px</span> <span style="color: #993333;">solid</span> <span style="color: #cc00cc;">#327E04</span><span style="color: #00AA00;">;</span>
    <span style="color: #000000; font-weight: bold;">background</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">transparent</span> <span style="color: #993333;">url</span><span style="color: #00AA00;">&#40;</span><span style="color: #ff0000; font-style: italic;">active-state.png</span><span style="color: #00AA00;">&#41;</span> <span style="color: #933;"><span style="color: #cc66cc;">50</span>%</span> <span style="color: #933;"><span style="color: #cc66cc;">50</span>%</span> <span style="color: #993333;">repeat-x</span><span style="color: #00AA00;">;</span>
    <span style="color: #000000; font-weight: bold;">font-weight</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">normal</span><span style="color: #00AA00;">;</span>
    <span style="color: #000000; font-weight: bold;">color</span><span style="color: #00AA00;">:</span> <span style="color: #cc00cc;">#ffffff</span><span style="color: #00AA00;">;</span>
    <span style="color: #000000; font-weight: bold;">outline</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">none</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.disabled</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">cursor</span><span style="color: #00AA00;">:</span> not-allowed<span style="color: #00AA00;">;</span>
    -ms-filter<span style="color: #00AA00;">:</span> <span style="color: #ff0000;">&quot;progid:DXImageTransform.Microsoft.Alpha(Opacity=60)&quot;</span><span style="color: #00AA00;">;</span>
    filter<span style="color: #00AA00;">:</span> alpha<span style="color: #00AA00;">&#40;</span>opacity<span style="color: #00AA00;">=</span><span style="color: #cc66cc;">60</span><span style="color: #00AA00;">&#41;</span><span style="color: #00AA00;">;</span>
    opacity<span style="color: #00AA00;">:</span> <span style="color: #cc66cc;">0.6</span><span style="color: #00AA00;">;</span>
    -moz-user-input<span style="color: #00AA00;">:</span> disabled<span style="color: #00AA00;">;</span>
    -moz-user-focus<span style="color: #00AA00;">:</span> ignore<span style="color: #00AA00;">;</span>
    -moz-user-modifty<span style="color: #00AA00;">:</span> read-only<span style="color: #00AA00;">;</span>
    -khtml-user-modify<span style="color: #00AA00;">:</span> read-only<span style="color: #00AA00;">;</span>
    -webkit-user-modify<span style="color: #00AA00;">:</span> read-only<span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span></pre></div></div>

<p>Classes such as these are most useful for when theming various user interface widgets. We can use a group of semantic presentation classes to indicate the state of a widget such as default, hover, active, and disabled. As the user interacts with the page, we dynamically apply the appropriate class to the widget to represent its current state. This level of class consistency makes it easy to ensure that all nodes with a similar role or state will look the same across all widgets.</p>
<p>Like abstract classes, themed classes also create relationships, however these relationships are more targeted towards a node’s state as opposed to its role. This makes it simple to target nodes based on their current state, for instance active nodes:</p>

<div class="wp_syntax"><div class="code"><pre class="css" style="font-family:monospace;"><span style="color: #6666ff;">.overlay</span><span style="color: #6666ff;">.active</span> <span style="color: #6666ff;">.header</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #808080; font-style: italic;">/* target the header of active overlays */</span>
<span style="color: #00AA00;">&#125;</span>
<span style="color: #6666ff;">.overlay</span><span style="color: #6666ff;">.active</span> <span style="color: #6666ff;">.body</span> <span style="color: #00AA00;">&#123;</span>
    <span style="color: #808080; font-style: italic;">/* target the body of active overlays */</span>
<span style="color: #00AA00;">&#125;</span></pre></div></div>

<p>Here we can add additional rules to automatically style the descendants of a node based on its state without directly referencing the descendants in CSS via additional class names or in JavaScript via DOM traversal. </p>
<p>Progressive enhancement also falls under the cloud of themed classes as it can be utilized to bring greater aesthetics to your skin. It differs in the sense that a class will be responsible for providing a single detail (rounded corners, drop shadow, gradient backgrounds, etc.) to the theme in a cross-browser and consistent manner:</p>

<div class="wp_syntax"><div class="code"><pre class="css" style="font-family:monospace;"><span style="color: #6666ff;">.shadow</span> <span style="color: #00AA00;">&#123;</span>
    -khtml-box-shadow<span style="color: #00AA00;">:</span> <span style="color: #933;">0px</span> <span style="color: #933;">0px</span> <span style="color: #933;">10px</span> rgba<span style="color: #00AA00;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #00AA00;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #00AA00;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #00AA00;">,</span> <span style="color: #cc66cc;">0.5</span><span style="color: #00AA00;">&#41;</span><span style="color: #00AA00;">;</span>
    -webkit-box-shadow<span style="color: #00AA00;">:</span> <span style="color: #933;">0px</span> <span style="color: #933;">0px</span> <span style="color: #933;">10px</span> rgba<span style="color: #00AA00;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #00AA00;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #00AA00;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #00AA00;">,</span> <span style="color: #cc66cc;">0.5</span><span style="color: #00AA00;">&#41;</span><span style="color: #00AA00;">;</span>
    -moz-box-shadow<span style="color: #00AA00;">:</span> <span style="color: #933;">0px</span> <span style="color: #933;">0px</span> <span style="color: #933;">10px</span> rgba<span style="color: #00AA00;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #00AA00;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #00AA00;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #00AA00;">,</span> <span style="color: #cc66cc;">0.5</span><span style="color: #00AA00;">&#41;</span><span style="color: #00AA00;">;</span>
    box-shadow<span style="color: #00AA00;">:</span> <span style="color: #933;">0px</span> <span style="color: #933;">0px</span> <span style="color: #933;">10px</span> rgba<span style="color: #00AA00;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #00AA00;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #00AA00;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #00AA00;">,</span> <span style="color: #cc66cc;">0.5</span><span style="color: #00AA00;">&#41;</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.corners</span> <span style="color: #00AA00;">&#123;</span>
    -khtml-border-radius<span style="color: #00AA00;">:</span> <span style="color: #933;">5px</span><span style="color: #00AA00;">;</span>
    -webkit-border-radius<span style="color: #00AA00;">:</span> <span style="color: #933;">5px</span><span style="color: #00AA00;">;</span>
    -moz-border-radius<span style="color: #00AA00;">:</span> <span style="color: #933;">5px</span><span style="color: #00AA00;">;</span>
    border-radius<span style="color: #00AA00;">:</span> <span style="color: #933;">5px</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span></pre></div></div>

<p>By grouping vendor specific styles together (-webkit-, -moz-, -o-, -ms-) nodes will adopt the behaviour in supported browsers and degrade gracefully in unsupported browsers. This helps to keep code not only backwards compatible but also future proof:</p>
<p>If properly implemented we can achieve visual consistency across an application and allow components to be themeable in a rather simplied and modular fashion.</p>
<h3>Summary</h3>
<p>When we combine all these techniques, we find utter simplicity in forming both the structure and skin of a node, while minimizing the amount of node specific style declarations in our stylesheet.  If done right, you will find your markup will greatly improve as a result and it will be as easy to write as the following:</p>

<div class="wp_syntax"><div class="code"><pre class="html4strict" style="font-family:monospace;"><span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;widget overlay corners shadow active&quot;</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;header content&quot;</span>&gt;</span>
        <span style="color: #808080; font-style: italic;">&lt;!-- header markup --&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;body content&quot;</span>&gt;</span>
        <span style="color: #808080; font-style: italic;">&lt;!-- body markup --&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;footer content&quot;</span>&gt;</span>
        <span style="color: #808080; font-style: italic;">&lt;!-- footer markup --&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span></pre></div></div>

<p>These techniques help to serve as an advantage not only to your CSS but also your markup and JavaScript for a truly unobtrusive implementation. To learn more techniques or to read further on a few I&#8217;ve discussed here, please refer to Nicole Sullivan&#8217;s <a href="http://oocss.org/" target="_blank">OOCSS</a> (Object-Oriented CSS) project, it is truly a great read and highly recommended.</p>
]]></content:encoded>
			<wfw:commentRss>http://ryanmorr.com/archives/leveraging-the-most-out-of-css-classes/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Browser Detection: Necessary or Negligent?</title>
		<link>http://ryanmorr.com/archives/brower-detection-necessary-or-negligent</link>
		<comments>http://ryanmorr.com/archives/brower-detection-necessary-or-negligent#comments</comments>
		<pubDate>Sun, 29 Mar 2009 22:27:28 +0000</pubDate>
		<dc:creator>Ryan Morr</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[Event]]></category>

		<guid isPermaLink="false">http://ryanmorr.com/?p=819</guid>
		<description><![CDATA[It is still a controversial issue today despite the recent evolutions in the industry including new modern browsers and new resources such as jQuery (as of version 1.3) that now entirely base their implementations on feature testing. However, somehow the practice of browser detection seems to still be alive and well, whether it be new [...]]]></description>
			<content:encoded><![CDATA[<p>It is still a controversial issue today despite the recent evolutions in the industry including new modern browsers and new resources such as jQuery (as of version 1.3) that now entirely base their implementations on feature testing. However, somehow the practice of browser detection seems to still be alive and well, whether it be new browsers bringing about new bugs, features that are difficult to detect, or simply shortcuts spawned out of pure laziness, the practice is not only being used but defended. Browser sniffing can be found around just about every corner you look &#8211; from the smallest of websites, to your favourite JavaScript library (Mootools, Prototype, YUI, etc.) utilized in corporate giants such as Chrysler, Gamespot, and Yahoo!<span id="more-819"></span></p>
<h3>What is Browser Detection?</h3>
<p>Browser detection or sniffing is the practice of detecting the browser runtime environment in which JavaScript is being executed. This helps to restrict execution of certain fragments of code to that browser based on features or bugs that are believed to be associated with that specific browser. This exercise is not only restricted to the type of browser (IE, Firefox, Opera, Safari, etc.) but also the browser version and the operating system. The most common method of detecting the browser is via the <em>userAgent</em> string of the <em>navigator</em> object, for example, the following is the output of the <em>userAgent</em> string of your browser:</p>
<p><script type="text/javascript"><!--
document.write(navigator.userAgent);
// --></script></p>
<p>As you can tell, you will be required to parse that string to get a definitive browser and version out of it.  Some developers will choose to ignore the user agent electing instead to facilitate unrelated object inference to detect the browser, such as ActiveXObject for Internet Explorer, despite common belief this should not be considered object detection.</p>
<p>The goal of browser detection is too provide a simple method in which to detect a browser&#8217;s native feature or method support (XMLHttpRequest, ActiveX, etc.), object support (event.clientX, event.pageX, etc.), and most importantly bugs (IE can confuse id and name attributes when using document.getElementById).</p>
<h3>The Dangers</h3>
<p>The practice of browser detection is nothing new and from the perspective of a relatively new developer to the language, it is a justified solution to obtain cross-browser compatibility which can be so difficult to achieve. However at some point along the way, the exercise has been abused, quickly becoming common routine rather than a last resort, finding its way into scripts where simple object detection would suffice.</p>
<p>The fundamental problem with browser detection in any capacity is the inherent dependency on what is widely believed to be true associations between a browser and a bug or feature. In other words, you are making an assumption about every browser of every user that visits the page, and assuming every feature and bug that is being tested for is a correct affiliation with that browser. These assumptions as always can be very dangerous, your application as a whole may just depend on it.</p>
<p>The flaw in browser detects themselves are their static nature, whether your testing the user agent or relying on a specific object  (ActiveXObject) to identify the browser, a static browser detect is only as reliable as your knowledge of the browser environments you currently support at the time of implementation. As browsers continue to evolve, new browser and browser versions released, and API&#8217;s updated, your application will become a fragile implementation at the mercy of the evolution. What were previously thought to be true associations between a browser and a feature or bug are now false and inconsistent.</p>
<p>Browser spoofing is an issue developers have been tackling ever since the days of Internet Explorer and Netscape Navigator. What is browser spoofing? Well, quite simply it is the ability for one browser to attempt to imitate another via the <em>userAgent</em> string. If you re-examine the example I provided above of what your user agent is, you may notice (depending on the browser your using) hints of other browsers. A quick test in the various browsers for me reveals words such as &#8220;Mozilla&#8221; in IE7 and  &#8220;Gecko&#8221; and &#8220;Safari&#8221; in Chrome. This makes it very difficult to create a reliable and consistent browser detect, requiring a developer to constantly change their methods of browser detection. To view the history of the user agent string and browser spoofing, see <a href="http://webaim.org/blog/user-agent-string-history/" target="_blank">http://webaim.org/blog/user-agent-string-history/</a></p>
<p>The ultimate goal of any application is to increase and maintain traffic, this starts with attempting to support as many browsers as possible. Typically, browser detection infers a specific list of supported browsers as is the case with most JavaScript libraries. However, this not only isolates your browser support but also alienates alternative browsers and browser versions that may otherwise be fully capable of supporting your application. Upgrading your browser version may be all that is required to break the browser sniff and all subsequent dependencies. Ideally, you should aim to support any browser that supports only the features your application utilizes, and offers a graceful degradation for those that do not.</p>
<p>It should also be noted that the greatest discrepancies between browsers is in rendering of the web page, which is not so much a JavaScript issue but a CSS and markup issue, so lets keep it that way. Making adjustments to various measured CSS properties such as width and height in JavaScript based on the type of browser should not be necessary. Of course there are the well known asterisk and underscore hacks, as well as many other browser specific workarounds in CSS, but that is another topic for another day.</p>
<h3>Feature Testing</h3>
<p>The ultimate solution and alternative to browser detection is feature testing, the simple means of testing for a &#8220;feature&#8221; before utilizing it in some capacity. The technique is often applied as direct object, method, or typeof inference as it relates to the feature within the browser environment during runtime. Ultimately, the reliability of such a test case lies solely in it&#8217;s ability to execute successfully and provide a definitive boolean value in which to compare against. However, there is a right way and wrong way in which to approach this technqiue, for instance, evaluting support for event handlers typically will involve a test case for standards compliant browsers such as Firefox and falls back to IE&#8217;s implementation if addEventListener is not supported:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> addEvent<span style="color: #000000;">&#40;</span>el<span style="color: #000000;">,</span> type<span style="color: #000000;">,</span> fn<span style="color: #000000;">&#41;</span>
    <span style="color: #003366; font-weight: bold;">if</span><span style="color: #000000;">&#40;</span>el.<span style="color: #006600;">addEventListener</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
        el.<span style="color: #006600;">addEventListener</span><span style="color: #000000;">&#40;</span>type<span style="color: #000000;">,</span> fn<span style="color: #000000;">,</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">;</span>
    <span style="color: #000000;">&#125;</span><span style="color: #003366; font-weight: bold;">else</span><span style="color: #000000;">&#123;</span>
        el.<span style="color: #006600;">attachEvent</span><span style="color: #000000;">&#40;</span><span style="color: #3366CC;">'on'</span> <span style="color: #000000;">+</span> type<span style="color: #000000;">,</span> fn<span style="color: #000000;">&#41;</span><span style="color: #000000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>However, even a perfectly suited feature test as common as this is making an assumption about the user&#8217;s browser; if it doesn&#8217;t support addEventListener, it must be IE, so lets use the attachEvent implementation. Ideally, a test case should be used for each browser specific implementation, and provide a final fallback on the off chance of a failed test case in an alien browser:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> addEvent<span style="color: #000000;">&#40;</span>el<span style="color: #000000;">,</span> type<span style="color: #000000;">,</span> fn<span style="color: #000000;">&#41;</span>
    <span style="color: #003366; font-weight: bold;">if</span><span style="color: #000000;">&#40;</span>el.<span style="color: #006600;">addEventListener</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
        el.<span style="color: #006600;">addEventListener</span><span style="color: #000000;">&#40;</span>type<span style="color: #000000;">,</span> fn<span style="color: #000000;">,</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">;</span>
    <span style="color: #000000;">&#125;</span><span style="color: #003366; font-weight: bold;">else</span> <span style="color: #003366; font-weight: bold;">if</span><span style="color: #000000;">&#40;</span>el.<span style="color: #006600;">attachEvent</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
        el.<span style="color: #006600;">attachEvent</span><span style="color: #000000;">&#40;</span><span style="color: #3366CC;">'on'</span> <span style="color: #000000;">+</span> type<span style="color: #000000;">,</span> fn<span style="color: #000000;">&#41;</span><span style="color: #000000;">;</span>
    <span style="color: #000000;">&#125;</span><span style="color: #003366; font-weight: bold;">else</span><span style="color: #000000;">&#123;</span>
        el<span style="color: #000000;">&#91;</span><span style="color: #3366CC;">'on'</span> <span style="color: #000000;">+</span> type<span style="color: #000000;">&#93;</span> <span style="color: #000000;">=</span> fn<span style="color: #000000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>The only problem here is that the third case actually sets the event not adds to it, so it effectively removes previously bound handlers of that event type. However this can be quickly solved by caching event handlers of a specific event type, in which case addEventListener and attachEvent would be completely unnecessary, such is the case with <a href="http://dean.edwards.name/weblog/2005/10/add-event/" target="_blank">Dean Edwards&#8217; solution</a>. Ultimately, this method combined with an unobtrusive implementation will almost certainly provide a reliable application suited for both browsers that support the method and those that don&#8217;t via graceful degradation, including the crowd that has disabled JavaScript.</p>
<p>The wild card are the various bugs or quirks; supported implementations that either do not perform or behave as expected. More often than not, a bug exists within a host method, meaning the only way it can possibly be tested is to actually execute the method in a meaningful test case, for example:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">try</span><span style="color: #000000;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> children <span style="color: #000000;">=</span> document.<span style="color: #006600;">documentElement</span>.<span style="color: #006600;">childNodes</span><span style="color: #000000;">;</span>
        <span style="color: #003366; font-weight: bold;">return</span> <span style="color: #009999;">Array</span>.<span style="color: #006600;">prototype</span>.<span style="color: #006600;">slice</span>.<span style="color: #006600;">call</span><span style="color: #000000;">&#40;</span>children<span style="color: #000000;">&#41;</span> <span style="color: #003366; font-weight: bold;">instanceof</span> <span style="color: #009999;">Array</span><span style="color: #000000;">;</span>
    <span style="color: #000000;">&#125;</span><span style="color: #003366; font-weight: bold;">catch</span><span style="color: #000000;">&#40;</span>e<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span><span style="color: #000000;">&#125;</span>
    <span style="color: #003366; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #000000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This particular test determines support for a native nodelist to array conversion. The method utilizes a try-catch block which typically should be avoided, primarily because in a context such as this, an assumption is being made about what it means when a test fails and the exception is caught. We assume that the exception was thrown and the method returned false because the browser doesn&#8217;t support native array conversions. However the method would return the same if an error occurred due to a bug else where in the try-catch block, this makes for fragile code in future browser environments. Although the solution is not ideal, it is the best JavaScript will allow us do at this point in time so it will have to do.</p>
<p>Despite difficult and often cumbersome, there is almost always a test case available in some capacity capable of determining browser support. To view more common bugs as well as their respective test cases, have a look at <a href="http://yura.thinkweb2.com/cft/" target="_blank">Juriy Zaytsev&#8217;s fantastic resource</a>.</p>
<p>Feature testing isn&#8217;t the perfect solution &#8211; there is no perfect solution, however from a practical standpoint, it is your best bet to ensure a reliable code base. As it relates to testing bugs, the dependency in the test will lie solely in the method in which you test the feature. The bottom line is if there is one thing that a developer should know; it&#8217;s the environment that he or she is dealing with. It is of far greater importance that a developer know the bugs and how to individually avoid them than to lump them all together based on assumptions in an eventual failure. To read more about feature testing, see <a href="http://peter.michaux.ca" target="_blank">Peter Michaux</a>&#8217;s excellent and all inclusive article on <a href="http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting" target="_blank">feature detection</a>.</p>
<h3>Summary</h3>
<p>Feature testing may not be simple and in some cases may require an elaborate and complicated test case, however it is the obvious answer. As oppossed to browser detection, it doesn&#8217;t draw on associations, assumptions, or false positives that are believed to be true affilations with a specific browser to create fragile test cases. Instead, feature testing relies on what it knows about the browser environment during runtime, not the precieved browser support at the time of implementation. The philosophy here is simple; if your unsure that a specific object/method is supported in the native environment or performs as expected, try it and let the test case tell you &#8211; don&#8217;t tell it. Resorting to browser detection should no longer be considered a last resort, but bad practice.</p>
]]></content:encoded>
			<wfw:commentRss>http://ryanmorr.com/archives/brower-detection-necessary-or-negligent/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Library or no Library, That is the Question!</title>
		<link>http://ryanmorr.com/archives/library-or-no-library-that-is-the-question</link>
		<comments>http://ryanmorr.com/archives/library-or-no-library-that-is-the-question#comments</comments>
		<pubDate>Sun, 08 Mar 2009 08:41:55 +0000</pubDate>
		<dc:creator>Ryan Morr</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[Event]]></category>
		<category><![CDATA[FX]]></category>

		<guid isPermaLink="false">http://ryanmorr.com/?p=720</guid>
		<description><![CDATA[It is rarely even a question anymore; deciding whether to use a JavaScript library on your next project typically goes without saying, the real question developers find themselves asking is which library should it be? However the decision to adopt any framework for a project should not be taken lightly and deserves a proper evaluation [...]]]></description>
			<content:encoded><![CDATA[<p>It is rarely even a question anymore; deciding whether to use a JavaScript library on your next project typically goes without saying, the real question developers find themselves asking is which library should it be? However the decision to adopt any framework for a project should not be taken lightly and deserves a proper evaluation of requirements before making a decision based on assumptions. Often a library may ask of a developer, &#8220;Does the JavaScript library help me to write JavaScript?&#8221;, but shouldn&#8217;t they ask if the library helps them to learn JavaScript? Learning the syntax of your favourite JavaScript library does nothing for the developer&#8217;s understanding of the language itself or the impact on performance, memory, and reliability of their implementations. For this article, I will be looking at both sides of the argument, but hiding my bias will not be easy, my hope here is that perhaps a few developer&#8217;s may rethink their approach.<span id="more-720"></span></p>
<h3>Why use a JavaScript Library?</h3>
<p>The driving force behind JavaScript libraries and their very rise in popularity is based on two things; cross-browser compatibility and the lack of various native implementations. They create an easy-to-use implementation which helps to normalize behaviour across browsers and add additional functionality, specifically as it relates to the the four core aspects of most JavaScript libraries; event handling, animation, DOM (manipulation and traversal), and AJAX.</p>
<p>Additionally, some libraries also feature, as a plugin or as part of the core, various user interface (UI) components and widgets, most notably jQuery UI, YUI, Digit (Dojo), and Ext.</p>
<p>The typical reasoning as to why a developer adopts any JavaScript library for their project falls back to the common expression; why reinvent the wheel?</p>
<h3>The Criteria</h3>
<p>Evaluating a JavaScript library is no different than an evaluation of your own code, after all, once implemented, you will assume responsibility for it. Performance, compatibility, and bugs will immediately become your problem &#8211; it is you who will hear the complaints of your end users, not the authors of the third party software you&#8217;ve decided to utilize. Therefore, it is important to understand the flaws inherent in all JavaScript libraries and to properly justify your choice of implementation for a specific project.</p>
<p>With that in mind, it is important to outline the criteria when considering which framework to adopt or whether or not to use one at all. Much of the criteria including the weight of each measure will be specific to the project in question, most of which stemming from the scale of the project and the desired functionality. Does your project require certain UI components such as a grid, toolbar, or tabbed interface? Will my application require support for HTML, XML, SVG, flash, or canvas? These are just a few of the questions that should be evaluated on a case by case basis. In addition to that, there are several general questions a developer should ask of himself and the pending project that are relevant to any and all projects:</p>
<ul>
<li>the ease of implementation/updates (API)</li>
<li>browser support</li>
<li>file size (bytes)</li>
<li>documentation</li>
<li>performance</li>
<li>extensibility</li>
<li>robustness and modularity</li>
<li>stability and reliability</li>
<li>the developer&#8217;s overall capacity to understand and progress in their understanding of their implementations</li>
</ul>
<p>The last point is especially important and should not be glossed over, dependency is something you should steer away from &#8211; to understand all the code is to know how to fix/improve it, even if it isn&#8217;t your code.</p>
<h3>Advantages</h3>
<p>Without question, a well developed JavaScript library has many advantages over the alternative and provides the developer a simple layer of abstraction on which to develop their application.</p>
<p>One of the primary advantages to a JavaScript framework is the ease and simplicity of development and implementation. Whether it be prototypical/classical inheritance, CSS selectors, animation and effects, or creating a wrapper class for things like elements, AJAX requests, or what have you, a library typically allows you to make quick implementations in little time and little bytes.</p>
<p>As I mentioned above, cross-browser compatibility and normalization is perhaps the greatest attribute of any library. The developer need not worry about the flawed implementations of the various browsers or what functionality is supported or isn&#8217;t, let the library worry about that.</p>
<p>If you are to adopt any third-party software, well documented code and a highly adaptive API are key. Although it is completely dependent on the framework at hand, typically a library will supply solid documentation set with examples.</p>
<p>Plugins, extensions, and user interface widgets are just a few of the byproducts of a healthy and active community. Extensibility plays a large role in developing and maintaining a community of developers for a specific library, and nobody does this better than jQuery. The library boasts an impressive amount of plugins ranging anywhere from drag-and-drop and layouts to data stores and media. With a community as active as that, virtually anything you could ever want is already available and ready for implementation.</p>
<p>Most of the JavaScript libraries available today are completely open-sourced, including; jQuery, Mootools, Prototype, YUI, Dojo, Ext, and more. Not only does this help to create an active community but can also help a developer in understanding how the framework implemented a certain feature by simply viewing the source and reading the documentation. It proves to be a very useful resource for anyone looking to learn and understand advanced JavaScript.</p>
<h3>Disadvantages</h3>
<p>At some point in the last four or five years, as the library revolution started to take over, too much attention has been placed on the positives and not enough focused on the negatives. These libraries are often portrayed as perfect, but they are not, and you should understand all the disadvantages inherent in their adoption for a project.</p>
<p>First and foremost, browser detection is a common problem amongst JavaScript libraries, and virtually all still utilize it. There is no feature/bug that can&#8217;t be detected, tested for, or worked around in some manner. Sacrificing bytes for shortcuts should never be permitted especially amongst the very best the industry has to offer. The goal should be to try and support as many browsers as possible, otherwise you could be turning away potential visitors without even knowing it. I would be remissed if I didn&#8217;t mention that jQuery (as of version 1.3) no longer utilizes browser sniffing as part of the base library, however many plugins still do!</p>
<p>Bugs are a common problem with any code, however when it isn&#8217;t your code and you don&#8217;t understand the implementations, your limited in your ability to resolve the bug. Such is the case with JavaScript libraries, a developer may find himself waiting for a new version or update of a specific framework to solve his bug as visitors continue to encounter the problem. Once that new version is released and implemented, he better cross his fingers and hope it gels well with not only his code, but any other plugins that also rely on that particular library. Often a library will release a version that unexpectedly drops support for specific methods, properties, and/or classes, forcing plugin developers to update their versions (which you will also have to wait for) unless you try and do it yourself.</p>
<p>Another common problem various JavaScript libraries internally struggle with is the battle between usability/simplicity (API) and performance. The layer of abstraction your working with may be on such a high level that the length and intensity of each method call is slower than it otherwise should be, specifically as it relates to DOM manipulation. For instance, jQuery contains all currently selected elements within an internal array that must be looped through on each method call, whether the array contains 100 items or 1 or 2, this creates unnecessary overhead. Although it is true that libraries consistently improve in this regard, performance still lacks where typical manual DOM manipulation excels, especially in IE. Just look at these performance results conducted by <a href="http://webreflection.blogspot.com/2009/04/taskspeed-dom-vs-libraries.html">Anrea Giammarchi </a>in a test that pits the various JavaScript libraries against the DOM.</p>
<p>A JavaScript framework is often guilty of trying to do too much, resulting in a bloated library of methods and classes that are rarely utilized, trying to answer questions nobody has asked.  Whats worse, is the encouragement and support for bad programming, trying to normalize behaviour not only amongst browsers but developers too. Of course, this results in a larger file size full of unused code &#8211; wasted bytes using unnecessary bandwidth. On a related note, many developers will use a JavaScript library solely for its support of a specific plugin, such as a lightbox or date picker. This requires them to import a large framework the majority of which is never utilized and therefore never justified.</p>
<p>As I mentioned before, the adoption of any JavaScript library does not progress a developer in the understanding of the language or the various implementations. It creates a certain level of dependence on methods, classes, and plugins that may not be there forever, as you fall at the mercy of the third party software. Sooner or later, the JavaScript language along with browser support will grow and improve, JavaScript libraries will quickly become obsolete in that environment, and any developers who rely on them will be left out in the cold &#8211; with their app of course.</p>
<h3>The Solution</h3>
<p>Ultimately the solution lies in learning the language and not a library, to know the bugs, the browser inconsistencies, and the supported implementations and knowing what to do about it. However, I realize that it is a time consuming goal that may not be realistic for the short term, that is why I propose a middle man; the module, think of it as a plugin for the language not a library.</p>
<p>Perhaps its a lack of support for lightweight and standalone modules that have driven people to the all inclusive framework and the various plugins that lie on top of them, in part this blog is dedicated to fill that void. Still third party software, a module however is small and concise and serves only one purpose, whether it be DOM manipulation, event handling, AJAX requests, or what have you. This makes for a much simpler approach and therefore easy debugging, not to mention, the author is more likely to update with greater frequency, plus no pesky dependencies.</p>
<p>Naturally, as many modules are thrown together, cohesion is likely to be effected resulting in code duplication and loose coupling, that is where you come in. Make it cohesive, merge the modules and create something custom for each project, your not reinventing the wheel but your also not relying on someone else&#8217;s. Take the tire, the rim, nuts and bolts and put it together yourself! You might learn something in the process!</p>
<p>Development is about one thing; to have a better understanding of what is going on behind the scenes, know your implementations and understand their impacts. The ultimate goal is the satisfaction of your end-user, and at the end of the day reliability should be your number one concern. For this, the answer is clear.</p>
]]></content:encoded>
			<wfw:commentRss>http://ryanmorr.com/archives/library-or-no-library-that-is-the-question/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Scope/Context in Javascript</title>
		<link>http://ryanmorr.com/archives/scope-context-in-javascript</link>
		<comments>http://ryanmorr.com/archives/scope-context-in-javascript#comments</comments>
		<pubDate>Mon, 09 Feb 2009 03:09:00 +0000</pubDate>
		<dc:creator>Ryan Morr</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[Event]]></category>

		<guid isPermaLink="false">http://ryanmorr.com/?p=464</guid>
		<description><![CDATA[Scope or context as it is often referred to as is one of the fundamental aspects of Javascript, playing a significant role unlike that of any other language. Scope refers to the accessibility of variables and its execution context which belongs to the object or function in which it was defined. However this does not [...]]]></description>
			<content:encoded><![CDATA[<p>Scope or context as it is often referred to as is one of the fundamental aspects of Javascript, playing a significant role unlike that of any other language. Scope refers to the accessibility of variables and its execution context which belongs to the object or function in which it was defined. However this does not always hold true as scope can be lost or changed depending on how and where it used, specifically as it applies to functional execution.<span id="more-464"></span></p>
<p>Each invocation of a function establishes a unique execution context that lasts only for the duration of that function call. Each execution context appends its local scope to the scope chain in which it was defined. Name conflicts amongst variables within a specific context are resolved by climbing up the scope chain, moving locally to globally. This means that local variables with the same name as variables higher up the scope chain take precedence.</p>
<h3>Global/Local Scope</h3>
<p>A variable can be defined in either local or global scope, which establishes the variables&#8217; accessibility and context within the runtime environment. Any defined global variables, meaning any variables declared outside of a function body live throughout the life of the page and can be accessed and altered in any context.</p>
<p>Local variables exist only within a function body of which they are defined via the var keyword and will have a different execution context for every call of that function. There it is subject for value assignment, retrieval, and manipulation only within that call and is not accessible outside of that execution context.</p>
<h3>Losing Scope</h3>
<p>It&#8217;s a common problem developers find themselves dealing with when they delve into advanced techniques in JavaScript, specifically as it refers to event handling and object orientation. Here the infamous <em>this</em> keyword plays an important role, but knowing what it is referring to at all times can be confusing.</p>
<p>Event handlers added using Internet Explorer&#8217;s attachEvent method causes a loss of scope when that event is fired and the callback is invoked, as the function is executed in the context of the window object. As a result, <em>this</em> will reference the window and not the element which registered the event handler as is the case with standards compliant browsers such as Firefox. Alternatively, when an event handler is added as an expando property (element.onclick), the callback will execute in the context of the element, even in IE. The reason for this is the scope chain, because the expando is a  property of the source element, it is appended at the top of the scope chain for each execution context. Meanwhile, due to a flaw in attachEvent, the window object is the only object associated with the callback and therefore is the only context available in the callback&#8217;s scope chain.</p>
<p>To better demonstrate this, try adding a function as a unique expando property and then execute it; <em>this</em> will now refer back to the source element:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> fn <span style="color: #000000;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
    <span style="color: #003366;">alert</span><span style="color: #000000;">&#40;</span><span style="color: #003366; font-weight: bold;">this</span>.<span style="color: #006600;">id</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">;</span> <span style="color: #009900; font-style: italic;">// foo</span>
<span style="color: #000000;">&#125;</span><span style="color: #000000;">;</span>
&nbsp;
element.<span style="color: #006600;">id</span> <span style="color: #000000;">=</span> <span style="color: #3366CC;">'foo'</span><span style="color: #000000;">;</span>
element<span style="color: #000000;">&#91;</span><span style="color: #3366CC;">'e'</span><span style="color: #000000;">+</span>fn<span style="color: #000000;">&#93;</span> <span style="color: #000000;">=</span> fn<span style="color: #000000;">;</span>
element<span style="color: #000000;">&#91;</span><span style="color: #3366CC;">'e'</span><span style="color: #000000;">+</span>fn<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">;</span></pre></div></div>

<p>Scope is also lost when dealing with object-orientation and event handling, which is not so much a flaw in the language but the implementation. Event handlers can only be added to DOM nodes which means (in standards-compliant browsers) <em>this </em>will always refer back to the source element, which is the way it should be. However if the callback happens to be an instance method, there is no way to properly call that method without altering scope. A quick solution to this is to declare a variable with the value of <em>this</em> and simply use a nested function to redirect the call to the desired method, like so:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> self <span style="color: #000000;">=</span> <span style="color: #003366; font-weight: bold;">this</span><span style="color: #000000;">;</span>
element.<span style="color: #006600;">onclick</span> <span style="color: #000000;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
    self.<span style="color: #006600;">instanceMethod</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>However, this can be cumbersome, the real solution involves what many believe to be one of the most useful techniques of the JavaScript langauge; manual scope adjustment (more on than a little further down in the article).</p>
<h3>Closures</h3>
<p>One of the most powerful aspects to JavaScript is the flexibility of functions; they can be sent as arguments, nested inside other functions, executed in any context desired, and encapsulate their own execution context. Closures can serve as quite the tool when scope becomes an issue as they can take on many different forms and can encapsulate and preserve a specific execution context for further manipulation.  In simplest terms, closures are variable functions that have the unique ability to retain their values between function calls. It does this by immediately invoking the function and returning an accessor capable of manipulating the variables the closure contains from the initial invocation. One of the most popular types of closures is what is widely known as the module pattern; it allows you to simulate public, private, and privileged members.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Module <span style="color: #000000;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> privateProp <span style="color: #000000;">=</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #000000;">;</span>
    <span style="color: #003366; font-weight: bold;">var</span> privateMethod <span style="color: #000000;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #000000;">&#40;</span>args<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
        <span style="color: #009900; font-style: italic;">//do something</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">return</span> <span style="color: #000000;">&#123;</span>
&nbsp;
        publicProp<span style="color: #000000;">:</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #000000;">,</span>
&nbsp;
        publicMethod<span style="color: #000000;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #000000;">&#40;</span>args<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
            <span style="color: #009900; font-style: italic;">//do something</span>
        <span style="color: #000000;">&#125;</span><span style="color: #000000;">,</span>
&nbsp;
        privilegedMethod<span style="color: #000000;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #000000;">&#40;</span>args<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
            privateFunction<span style="color: #000000;">&#40;</span>args<span style="color: #000000;">&#41;</span><span style="color: #000000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span></pre></div></div>

<p>The module acts as if it were a singleton executed as soon as the compiler interprets it (hence the opening and closing parenthesis at the end of the function). The only available members outside of the execution context of the closure are your public methods and properties located in the return object (ex. Module.publicMethod). However, all private properties and methods will live throughout the life of the application as the execution context is preserved, meaning variables are subject to further manipulation and execution via the public methods. Another type of closure is what I like to call a global closure which is nothing more than a self-invoked anonymous function executed in the context of the window:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000000;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
&nbsp;
    <span style="color: #009900; font-style: italic;">//Use this or window to define a global variable</span>
    <span style="color: #003366; font-weight: bold;">var</span> Module <span style="color: #000000;">=</span> <span style="color: #003366; font-weight: bold;">this</span>.<span style="color: #006600;">Module</span> <span style="color: #000000;">=</span> window.<span style="color: #006600;">Module</span> <span style="color: #000000;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
        <span style="color: #009900; font-style: italic;">//do something</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    Module.<span style="color: #006600;">publicProp</span> <span style="color: #000000;">=</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #000000;">;</span>
    Module.<span style="color: #006600;">publicMethod</span> <span style="color: #000000;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
        <span style="color: #009900; font-style: italic;">//do something</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">var</span> privateProp <span style="color: #000000;">=</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #000000;">;</span>
    <span style="color: #003366; font-weight: bold;">var</span> privateMethod <span style="color: #000000;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
        <span style="color: #009900; font-style: italic;">//do something</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span></pre></div></div>

<p>The global closure is most useful when attempting to preserve the global namespace as any variables declared within the function body will be local to the closure but will still live throughout runtime, often one namespace is enough for interaction outside of the closure.</p>
<h3>Call and Apply</h3>
<p>If you want to know how all the mainstream libraries do it, well it&#8217;s simple; call and apply. These two very simple methods inherent to all functions allow you to execute any function in any desired context. Before I continue, it is important to know that everything in JavaScript inherently has its own context, including DOM nodes, objects, arrays, strings, functions, etc. Meaning, any function can be executed in the context of any object using call and apply. This may seem insignificant, but understand it is this implementation that serves as an underlying bridge between the object-oriented and functional methodologies in the JavaScript language.</p>
<p>The call method contains an unspecified amount of arguments, the first is the object whose context the function is to be executed in, all subsequent arguments will serve as the arguments for the callback function in question. Apply works similarly with one exception, rather than supplying each argument individually, an array will be supplied that will automatically build the arguments for the function.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">method.<span style="color: #006600;">call</span><span style="color: #000000;">&#40;</span>scope<span style="color: #000000;">,</span> arg1<span style="color: #000000;">,</span> arg2<span style="color: #000000;">,</span> arg3<span style="color: #000000;">&#41;</span><span style="color: #000000;">;</span>
method.<span style="color: #006600;">apply</span><span style="color: #000000;">&#40;</span>scope<span style="color: #000000;">,</span> <span style="color: #000000;">&#91;</span>args<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">;</span></pre></div></div>

<p>This is ultimately what should be used when referring to event handlers especially as it relates to object-orientation. One of the more popular functions used to quickly adjust context is the bind function, which utilizes closures by accepting the scope as well as arguments for the callback function and returning an anonymous function that behaves appropriately.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">Function</span>.<span style="color: #006600;">prototype</span>.<span style="color: #006600;">bind</span> <span style="color: #000000;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> method <span style="color: #000000;">=</span> <span style="color: #003366; font-weight: bold;">this</span><span style="color: #000000;">;</span>
    <span style="color: #003366; font-weight: bold;">var</span> context <span style="color: #000000;">=</span> arguments<span style="color: #000000;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">;</span>
    <span style="color: #003366; font-weight: bold;">var</span> args <span style="color: #000000;">=</span> <span style="color: #009999;">Array</span>.<span style="color: #006600;">prototype</span>.<span style="color: #006600;">slice</span>.<span style="color: #006600;">call</span><span style="color: #000000;">&#40;</span>arguments<span style="color: #000000;">,</span> <span style="color: #CC0000;">1</span><span style="color: #000000;">&#41;</span>
    <span style="color: #003366; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
        method.<span style="color: #006600;">apply</span><span style="color: #000000;">&#40;</span>context<span style="color: #000000;">,</span> args<span style="color: #000000;">&#41;</span><span style="color: #000000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>It is most commonly used where context is most commonly lost; event handling as well as a few other implementations such as  setInterval and setTimeout. The following example demonstrates a callback method bound to a specific context for execution for each loop of an interval:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">setInterval<span style="color: #000000;">&#40;</span>callback.<span style="color: #006600;">bind</span><span style="color: #000000;">&#40;</span>obj<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">;</span></pre></div></div>

<p>What is important to note here is that setInterval is not executing the bind function or the callback function. In fact it is the closure that was returned by the bind function that is being called on each loop of the interval. It promptly redirects the call to the callback function in the context that was supplied to the bind function: &#8220;obj&#8221;. While reviewing the source of the bind function, you may have also noticed what appears to be a relatively simple line of code involving a method of the Array object&#8217;s prototype:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> args <span style="color: #000000;">=</span> <span style="color: #009999;">Array</span>.<span style="color: #006600;">prototype</span>.<span style="color: #006600;">slice</span>.<span style="color: #006600;">call</span><span style="color: #000000;">&#40;</span>arguments<span style="color: #000000;">,</span> <span style="color: #CC0000;">1</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">;</span></pre></div></div>

<p>What is interesting to note here is that the <em>arguments</em> object is not actually an array at all, however it is often described as an array-like object much like a nodelist (anything returned by getElementsByTagName or element.childNodes). They contain a length property and indexed values but they are still not arrays, and subsequently don&#8217;t support any of the native methods of arrays such as slice and push. However, because of their similar behaviour, the methods of Array can be hijacked and executed in the context of an array-like object as is the case above. However, depending on what methods your attempting to hijack and how you are specifically using them, you can run into some serious cross-browser inconsistencies and bugs including runtime errors.</p>
<p>This technique also applies to object-orientation; making it easy to execute a method of the prototype chain of a class in the context of another instance. The following example demonstrates a method of the Module class calling a method of the Component class in the context of the Module instance. This is also what makes calls to a superclass possible when simulating inheritance in JavaScript.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Module.<span style="color: #006600;">prototype</span>.<span style="color: #006600;">method</span> <span style="color: #000000;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
    <span style="color: #009900; font-style: italic;">//call another method of another class in the context of this instance</span>
    Component.<span style="color: #006600;">prototype</span>.<span style="color: #006600;">method</span>.<span style="color: #006600;">call</span><span style="color: #000000;">&#40;</span><span style="color: #003366; font-weight: bold;">this</span><span style="color: #000000;">,</span> arg1<span style="color: #000000;">,</span> arg2<span style="color: #000000;">,</span> arg3<span style="color: #000000;">&#41;</span><span style="color: #000000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h3>Summary</h3>
<p>Versatility is the name of the game here, in the attempt to try and do everything JavaScript fails to present developers with a well integrated language, resulting in a very loose implementation. However, there is a method to the madness, and although these little quirks and workarounds are not ideal they are necessary if you want that efficient and effective app that we all strive for. All the techniques I&#8217;ve discussed here today are powerful ones, and they can work against you if implemented in the wrong fashion or the wrong place. Closures for example can reserve a lot of memory and ultimately cause memory leaks in IE. However, when done right, developing will never be easier and it will show, knowing your scope at all times is important and to know it is to utilize it, which will save you a world of headaches now and in the future.</p>
<h3>References</h3>
<ul>
<li><a href="http://www.digital-web.com/articles/scope_in_javascript/" target="_blank">http://www.digital-web.com/articles/scope_in_javascript/</a></li>
<li><a href="http://www.robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/" target="_blank">http://www.robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/</a></li>
<li><a href="http://www.jibbering.com/faq/faq_notes/closures.html" target="_blank">http://www.jibbering.com/faq/faq_notes/closures.html</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://ryanmorr.com/archives/scope-context-in-javascript/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
