<?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"
	>

<channel>
	<title>agum &#187; AJAX</title>
	<atom:link href="http://www.agum.com/web/category/ajax/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.agum.com/web</link>
	<description>The Web Dev Blog</description>
	<pubDate>Mon, 23 Jun 2008 10:47:45 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5.1</generator>
	<language>en</language>
			<item>
		<title>JavaScript: Using Event Listeners, attaching handlers on page load, and DOMContentLoaded</title>
		<link>http://www.agum.com/web/2008/03/21/javascript-using-event-listeners-attaching-handlers-on-page-load-and-domcontentloaded/</link>
		<comments>http://www.agum.com/web/2008/03/21/javascript-using-event-listeners-attaching-handlers-on-page-load-and-domcontentloaded/#comments</comments>
		<pubDate>Sat, 22 Mar 2008 04:03:15 +0000</pubDate>
		<dc:creator>Bigi</dc:creator>
		
		<category><![CDATA[AJAX]]></category>

		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.agum.com/web/2008/03/21/javascript-using-event-listeners-attaching-handlers-on-page-load-and-domcontentloaded/</guid>
		<description><![CDATA[For anybody who has ever coded any JavaScript at all, they are no doubt familiar with events such as &#8220;onclick&#8221;, &#8220;onmouseover&#8221;, &#8220;onmousemove&#8221;, and more. In old HTML web pages, it was very common to add these attributes to &#60;a&#62; tags to achieve some special effects.
Later on, browsers begin to support these attributes even in other [...]]]></description>
			<content:encoded><![CDATA[<p>For anybody who has ever coded any JavaScript at all, they are no doubt familiar with events such as &#8220;onclick&#8221;, &#8220;onmouseover&#8221;, &#8220;onmousemove&#8221;, and more. In old HTML web pages, it was very common to add these attributes to &lt;a&gt; tags to achieve some special effects.</p>
<p>Later on, browsers begin to support these attributes even in other tags like &lt;div&gt;, and pretty much anything else.</p>
<p>However, as web standards develop over the years and people&#8217;s coding practices for the web begin to standardize, it is generally considered bad practice to use them. There are many reasons for this, among others:</p>
<ol>
<li>You cannot attach more than 1 action this way. If you want to do a lot of things in one event, you will need to put a lot of code either in this attribute, or in the function being called from this attribute; and these may very well be unrelated actions. This makes your code less organized and harder to develop.</li>
<li>No good separation of presentation (HTML) from functionality (JavaScript). Everything is mixed together. This makes collaboration development efforts difficult; and makes the code hard for you to manage even if you were the sole developer.</li>
</ol>
<p>Fortunately, we have an alternative solution. They are Event Listeners.</p>
<p><span id="more-30"></span><br />
<strong>Event Listeners basics</strong></p>
<p>Event listeners are initiated strictly in JavaScript code, not within any HTML tags.</p>
<p>For the remaining of this article, I will assume the use of the <a href="http://www.prototypejs.org/">Prototype.js</a> framework. I&#8217;m aware that there are advanced developers who dislike this library, but it is used fairly commonly (either completely, or their own in-house modified version) among a lot of startups and web apps, so hopefully it&#8217;s not unreasonable to depend on it.</p>
<p>With that in mind (with the inclusion of Prototype.js), you can initiate an event listener like this. Assuming you defined a function for handling the &#8220;click&#8221; event on a div block with an id &#8220;main_div&#8221;:</p>
<blockquote>
<pre>var handlerFunction = function(event) {
alert('Hello world!');
};</pre>
<pre>var my_box = document.getElementById('main_div');
Event.observe(my_box, 'click', handlerFunction);</pre>
</blockquote>
<p>The main idea is very simple. It is simply this: instead of using onclick (or on-* of any event) in any HTML tags, you have Event.observe in your JavaScript code instead. This way, you can add as many different functions as you like to any elements. They can even come from different .js files. (for more details on how to use Event.observe, see the <a href="http://www.prototypejs.org/api/event/observe">Prototype.js documentation</a>.)</p>
<p>To see what kind of events are available to you other than &#8220;click&#8221;, see the <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html">DOM Events W3C spec</a>. What you will often be using are in section 1.6.2, mouse events.</p>
<p><strong>Page loading, and Initialization routine</strong></p>
<p>If you understand what the above code means, you can also logically deduce that, your event handler does not start being observed until the point this JavaScript runs. And whether you want it or not, when the Event.observe line executes, it will start.</p>
<p>The implication here is that, it is entirely possible that your HTML document is not ready to handle this. This is because JavaScript runs linearly as your HTML file is being loaded and parsed.</p>
<p>More often than not, your JavaScript resides in the beginning of your file. (It is recommended for web developers to keep their JavaScript at the top)  That means you don&#8217;t even have any objects on your HTML page yet! Your Event.observe line is sure to fail, because the object by the id &#8220;main_div&#8221; does not exist yet.</p>
<p>So should you put your JavaScript at the end of your page instead? Of course not! What you want is a way to run all your Event.observe lines <em>after your page is fully loaded</em>.</p>
<blockquote>
<pre>Event.observe(window, 'load', function() {
Event.observe(my_box, 'click', handlerFunction);
// ... any other event listeners go here
});</pre>
</blockquote>
<p>Once you have this in your JavaScript, all your event listeners will only initiate after your page is completely loaded. The way this works is simple. The &#8220;window&#8221; element means the entire browser window. The &#8216;load&#8217; event for this element means that this handler function will execute when the page is done loading. So the effect is that all your interactive elements on your page will start being interactive when the page is fully loaded.</p>
<p><strong>DOMContentLoaded</strong></p>
<p>But there is still a problem! The key word in the last paragraph was &#8220;fully loaded&#8221;. What this means is, your interactive elements only work <em>after</em> your entire page is ready. Unfortunately, this means after all images and other binary data have finished loading. When your web page is heavy with data, this might be a long time. If you use event listeners for your navigation dropdown menus, for example, that means they are not going to work until all your images are done loading. It would be very annoying if a user cannot use your navigation menu before the page finishes loading.</p>
<p>*This is why I wrote this article!* The key point is here.</p>
<p>Fortunately, thanks to many wise web developers on the internet, we now have a solution. This solution lets you initialize your event listeners as soon as your HTML finishes loading, and <em>without having to wait for images and all other data on your page</em>.</p>
<p>The solution: <a href="http://tanny.ica.com/ICA/TKO/tkoblog.nsf/dx/domcontentloaded-for-browsers-part-iv">DOMContentLoaded</a>.</p>
<p>In simple words, this events.js library will let you do this:</p>
<blockquote>
<pre>addEvent(window, "DOMContentLoaded", function() {
Event.observe(...);
// ...
});</pre>
</blockquote>
<p>What will happen now is that, all your event listeners will initiate as soon as the HTML of your page is loaded, without having to wait for anything else. I am not going to go through the details of how and why here (I try to make my blog as close to practical usage lessons as possible without being too academic). If you are interested, the link I gave you above should give you every detail you want.</p>
<p><strong>Conclusion</strong></p>
<p>With all of the above knowledge, there is absolutely no reason one should be using the old ways of &#8220;onclick&#8221;, &#8220;onmouseover&#8221;, etc. anymore. Many people attempt to use event listeners, but oftentimes they encounter the problem I stated above of elements having to wait for the page to be fully loaded to become interactive. This has turned many people back to using the old-school methods, which is unhealthy.  After having introduced you to DOMContentLoaded, it should solve all concerns you have with using event listeners.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agum.com/web/2008/03/21/javascript-using-event-listeners-attaching-handlers-on-page-load-and-domcontentloaded/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.382 seconds -->
