<?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>buyco.ca &#187; Javascript</title>
	<atom:link href="http://www.buyco.ca/category/how-to/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.buyco.ca</link>
	<description>because someone stole my name</description>
	<lastBuildDate>Fri, 24 Jun 2011 01:23:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Leveraging JavaScript Frameworks to Make Your Life Easier</title>
		<link>http://www.buyco.ca/2009/08/28/leveraging-javascript-frameworks-to-make-your-life-easier/</link>
		<comments>http://www.buyco.ca/2009/08/28/leveraging-javascript-frameworks-to-make-your-life-easier/#comments</comments>
		<pubDate>Fri, 28 Aug 2009 09:51:44 +0000</pubDate>
		<dc:creator>Buyco</dc:creator>
				<category><![CDATA[Features]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Web Dev Tips and Tricks]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[mootools]]></category>
		<category><![CDATA[prototype]]></category>

		<guid isPermaLink="false">http://www.buyco.ca/?p=132</guid>
		<description><![CDATA[Are you all about programming in JavaScript? Save yourself some time and try implementing a scripting framework. ]]></description>
			<content:encoded><![CDATA[<h4>Framework Preface</h4>
<p>Are you a hardcore JavaScript/AJAX programmer who knows no bounds? Do you spend meticulous hours perfecting your code so it works on all browsers? I used to be like that. I still am, but the only difference is that I now don&#8217;t spend hours testing my code. This is mostly attributed to the Prototype framework. Today I&#8217;m going to go through a few features and benefits of using a JavaScript framework over writing custom code yourself which may require testing and re-testing. Of course there is still the need for testing even when using a framework, but the difference is that there will be a lot of cross-browser compliance which is no longer needed.
<p>There are other frameworks out there like jQuery and MooTools, but today we&#8217;ll start with what I&#8217;m more familiar with and with what I first started with. The documentation for Prototype is very thorough and I don&#8217;t want to explain everything, so I&#8217;ll start off with the major items which will change your JavaScript programming life!</p>
<h4>JavaScript Framework? Double you tee eff?</h4>
<p>You&#8217;re asking the right question. For the longest time I was always stuck in my own little JavaScript world where everything I coded was job-specific, customized, and with my own techniques. There were also little quirks which JavaScript had when rendering/running under different browsers/operating systems&#8211;these too were also solved using my own super secret techniques. What Prototype does, as well as other JavaScript frameworks, is give you the simple building-blocks which solve those quirks without you even needing to address them specifically. For example, if you want a <em>div</em> element to show or hide, you simply select the element and program the action. Sounds simple, but selecting that element requires some browser detection and compatibility verification. Let&#8217;s make a couple comparisons..</p>
<h4>Make your life easier</h4>
<p>Continuing on with the previous example, let&#8217;s select that <em>div</em> element given the following markup:</p>
<pre class="brush: xml">
&lt;div id="copy">
	&lt;p>Lorem ipsom dolor sit amet&lt;/p>
&lt;/div>
</pre>
<p>We&#8217;re not going to think of any invokers right now, let&#8217;s just try to hide the <em>div</em>. Here is what the JavaScript may have looked like prior to using Prototype:</p>
<pre class="brush: jscript;">
var objDivId = 'copy';
objDiv = document.layers ? document.layers[objDivId] : document.all ? document.all[objDivId] : document.getElementById ? document.getElementById(objDivId) : null;
objDiv != null ? objDiv.style.display = 'none' : '';
</pre>
<p>Obviously this isn&#8217;t the most efficient way of doing this, ideally I would create a function, but this is the shortest of shorthands to select and hide the <em>div</em> element while respecting all web browsers. Now let&#8217;s have a look at how this would look using the Prototype framework:</p>
<pre class="brush: jscript;">
var objDivId = 'copy';
objDiv = $(objDivId);
$(objDivId) ? $(objDivId).style.display = 'none' : '';
</pre>
<p>For this example, the difference is quite apparent. By using the $() utility method we can quickly select that <em>div</em> element without the worry of what browser is being used. Now, let&#8217;s see what happens when we try to hide more than one element. First here&#8217;s the HTML markup:</p>
<pre class="brush: xml">
&lt;div id="copy">
	&lt;p>Lorem ipsom dolor sit amet&lt;/p>
&lt;/div>
&lt;div id="button">
	&lt;p>This is a button&lt;/p>
&lt;/div>
&lt;div id="preview">
	&lt;p>This is a preview section&lt;/p>
&lt;/div>
</pre>
<p>I&#8217;m going to create a function to hopefully help the cause of the traditional JavaScript code and see how it compares to using Prototype. First the oldschool method:</p>
<pre class="brush: jscript;">
function getObject(id) {
	return document.layers ? document.layers[id] : document.all ? document.all[id] : document.getElementById ? document.getElementById(id) : null;
}
var objDivIds = new Array('copy','button','preview');
for (var i=0; i&lt;objDivIds.length; i++) {
	objDiv = getObject(objDivIds[i]);
	objDiv.style.display = 'none';
}
</pre>
<p>And now the code for doing the same thing using Prototype:</p>
<pre class="brush: jscript;">
$('copy','button','preview').invoke('hide');
</pre>
<p>Say what!? Yeah, it&#8217;s that easy. The traditional method utilizes a function which will return the object instance. We then iterate through the three <em>div</em> elements and update each one individually.</p>
<p>In the Prototype version, we&#8217;re using a couple of included extensions. First, the selector $() utility method returns an Enumerable list of objects, and the <em>hide</em> function is invoked across all of those objects. Easy fo-sheezy.</p>
<p>There are also other ways of selecting multiple elements within a page. You can do this by applying some CSS knowledge. For example, let&#8217;s attach a tracking script to all of the links within a page. We want to first select all of the <em>A</em> elements, then iterate through them by adding a short querystring tag to it&#8217;s <em>href</em> attribute.</p>
<pre class="brush: jscript;">
var _TAG = '?source=buyco.ca';
$$('a').each(function(objA) {
	var url = objA.getAttribute('href');
	objA.setAttribute('href',url+_TAG);
});
</pre>
<p>This time I&#8217;m using the $$() utility method which will select a collection of elements. It takes in CSS-style selectors, such as: &#8216;a.external&#8217; (select all a elements with the classname external), or &#8216;div#nav ul li&#8217; (select all list items in the div with the id of &#8216;nav&#8217;). The full documentation on this can be found on the <a href="http://www.prototypejs.org/api/utility" title="Prototype API" target="_blank">Prototype API documentation website</a>.</p>
<h4>Post face?</h4>
<p>These are two short examples of a few things you can do (quicker) by utilizing a JavaScript framework. You will spend less time focused on browser compliance and more on the functionality and interactivity of your websites. It&#8217;s not a quick transition, but practice does make perfect! The documentation on the <a href="http://www.prototypejs.org/" target="_blank" title="Prototype JS">Prototype website</a> is awesome, and I still find myself going back to learn new things. The main point I&#8217;m trying to get across here is that there are tools out there to make our lives (as web developers) a whole lot easier. Don&#8217;t get stuck in a place where you&#8217;re too comfortable or you&#8217;ll end up writing IE6-compliant code forever. Spend your time on more important things like user-experience, and wicked-awesome-flashy-effects. Your site visitors will thank you:)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.buyco.ca/2009/08/28/leveraging-javascript-frameworks-to-make-your-life-easier/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unobtrusive Image Rollover</title>
		<link>http://www.buyco.ca/2008/06/19/unobtrusive-image-rollover/</link>
		<comments>http://www.buyco.ca/2008/06/19/unobtrusive-image-rollover/#comments</comments>
		<pubDate>Thu, 19 Jun 2008 21:13:59 +0000</pubDate>
		<dc:creator>Buyco</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[addEventListener]]></category>
		<category><![CDATA[attachEvent]]></category>
		<category><![CDATA[hover]]></category>
		<category><![CDATA[mouseover]]></category>
		<category><![CDATA[unobtrusive]]></category>

		<guid isPermaLink="false">http://www.buyco.ca/?p=23</guid>
		<description><![CDATA[Learn how to add some spice to your site! Unobtrusive programming should be common practice, and what better way to start than here.]]></description>
			<content:encoded><![CDATA[<p>As web developers we spend so much time trying to make our sites cutting edge yet still functional with older browsers. It&#8217;s a curse! How great would it be to have a web browser standard that everyone could adhere to. Too bad life isn&#8217;t that simple. In today&#8217;s example we&#8217;re going to create a simple javascript image rollover. Yes, I know we&#8217;ve all done it before, but today we&#8217;ll do it right: unobtrusively.</p>
<p>There are many ways to do this, but in this example we&#8217;re just going to do a simple image replacement on mouseover. We&#8217;ll start off with the code for the image:</p>
<pre>&lt;img src="/images/how-to/javascript/button-inactive.gif" id="button" /&gt;</pre>
<p>For your SEO enthusiasts and W3C fiends, I know there are missing attributes. We&#8217;re going to go as minimalist as possible to simplify this process. One attribute to note of is the &#8220;id&#8221; which we&#8217;ll be using to select this particular image. This is very important so that we can select this image element based on it&#8217;s id (DOM FTW!).</p>
<p>Next we want to apply an event handler to that object so that when the user moves the cursor over it, the image will change into something pretty! Internet explorer uses a different type of event handler code than other browsers (because if it didn&#8217;t, this would be way too easy). So we will ensure we do a little browser detection:</p>
<pre>var isMoz;
window.addEventListener ? isMoz = true : isMoz = false;</pre>
<p>The window.addEventListener method is not used by Internet Explorer, so here we just single those browsers out. Next we want to create the code to attach a function to the mouseover (or onmouseover) event of the button. We haven&#8217;t created the image swapping functions yet, but keep in mind that we&#8217;ll call them imgOver and imgOut. That being said, lets create the event listeners and put them in a function called initMouseOver:</p>
<pre>function initMouseOver() {
 var objImage = document.getElementById('button');
 if (isMozilla) {
  objImage.addEventListener('mouseover', imgOver, false);
  objImage.addEventListener('mouseout', imgOut, false);
 }
 else {
  objImage.attachEvent('onmouseover', imgOver);
  objImage.attachEvent('onmouseout', imgOut);
 }
}</pre>
<p>Now you see why the image&#8217;s ID is important (remember: DOM FTW!). In the above snippet, when the function is called, event listeners are added to the image object. In addEventListener and attachEvent, the first value passed in is called the event type. For a mouse over event, these are valued at mouseover and onmouseover. The second value is the function to be associated with the event. In addEventListener the last value taken in is a boolean value which indicates whether or not to bind the event as it propogates to the image or as the event bubbles upwards from the image. This is usually set to false.</p>
<p>Next we need to create the functions to swap the images in and out as the object captures the events:</p>
<pre>function imgOver(e) {
 var eMoz = 'target';
 var eIE = 'srcElement';
 var objImgOver = new Image();
 objImgOver.src = '/images/how-to/javascript/button-active.gif';
 e[eMoz] ? e[eMoz].src = objImgOver.src : e[eIE].src = objImgOver.src;
}
function imgOut(e) {
 var eMoz = 'target';
 var eIE = 'srcElement';
 var objImgOut = new Image();
 objImgOut.src = '/images/how-to/javascript/button-inactive.gif';
 e[eMoz] ? e[eMoz].src = objImgOut.src : e[eIE].src = objImgOut.src;
}</pre>
<p>In both functions, we&#8217;re initializing the new image, then swapping it. This is not the most efficient way to do this since we&#8217;re recreating a new image object every time an event occurs. So let&#8217;s clean up all the code and put it into a separate javascript file. Here&#8217;s how it should look:</p>
<pre>var isMoz;
window.addEventListener ? isMoz = true : isMoz = false;
var eMoz = 'target';
var eIE = 'srcElement';
var objImgOver = new Image();
objImgOver.src = '/images/how-to/javascript/button-active.gif';
var objImgOut = new Image();
objImgOut.src = '/images/how-to/javascript/button-inactive.gif';

function initMouseOver() {
 var objImage = document.getElementById('button');
 if (isMozilla) {
  objImage.addEventListener('mouseover', imgOver, false);
  objImage.addEventListener('mouseout', imgOut, false);
 }
 else {
  objImage.attachEvent('onmouseover', imgOver);
  objImage.attachEvent('onmouseout', imgOut);
 }
}
function imgOver(e) {
 e[eMoz] ? e[eMoz].src = objImgOver.src : e[eIE].src = objImgOver.src;
}
function imgOut(e) {
 e[eMoz] ? e[eMoz].src = objImgOut.src : e[eIE].src = objImgOut.src;
}</pre>
<p>*Deep breath* still with me? That&#8217;s essentially it! All you need to do now is to include the javascript file in your HTML and ensure the initMouseOver() function is called when the page loads. Simply add onload=&#8221;" to your body tag and it should look a little something like this:</p>
<pre>&lt;body onload="javascript:initMouseOver();"&gt;</pre>
<p style="text-align: center;"><img id="button" class="aligncenter" src="/images/how-to/javascript/button-inactive.gif" alt="" /></p>
<p>That&#8217;s it! No wait&#8211;that&#8217;s only for one image. What if we need to set this up for multiple images? Well, glad I asked because there are several ways of accomplishing this. If you think you can take more of this, carry on to one of the next tutorials or download all the work files for this one:</p>
<blockquote><p><a title="Example: Unobtrusive Image Rollover" href="http://www.buyco.ca/downloads/how-to/javascript/example-unobtrusive-javascript-rollover.zip" target="_blank">Example: Unobtrusive Image Rollover</a></p></blockquote>
<p>Next step: multiple buttons, preloading, and optimization</p>
]]></content:encoded>
			<wfw:commentRss>http://www.buyco.ca/2008/06/19/unobtrusive-image-rollover/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

