<?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>klauskomenda.com &#187; Agent YUI</title>
	<atom:link href="http://www.klauskomenda.com/archives/category/web/coding/agent-yui/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.klauskomenda.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Wed, 14 Dec 2011 23:58:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Agent YUI: Mission 5 &#8211; Ajax. Shaken, not stirred.</title>
		<link>http://www.klauskomenda.com/archives/2008/07/26/agent-yui-mission-5-ajax-shaken-not-stirred/</link>
		<comments>http://www.klauskomenda.com/archives/2008/07/26/agent-yui-mission-5-ajax-shaken-not-stirred/#comments</comments>
		<pubDate>Sat, 26 Jul 2008 21:53:48 +0000</pubDate>
		<dc:creator>Klaus</dc:creator>
				<category><![CDATA[Agent YUI]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://www.klauskomenda.com/?p=214</guid>
		<description><![CDATA[It has been a while, but he is back. Agent YUI on a new exciting mission, equipped with a lot of gadgets, fighting the villain and seducing a couple of girls along the way. Well not quite. This time, we will discover how to use what is literally the dot in Web 2.0: Ajax.]]></description>
			<content:encoded><![CDATA[<p><a href="/archives/category/web/coding/agent-yui/">Missions 1 to 4</a> covered a lot of stuff already and gave the attentive reader a good idea what the <a href="http://developer.yahoo.com/yui/">YUI</a> is capable of and can do for you in everyday development. Today we will discover how to use a very important utility that is part of YUI and pretty essential these days in a world where Web 2.0 rules the world (there you have your villain): <a href="http://developer.yahoo.com/yui/connection/">YUI Connection Manager</a>. </p>
<h2>Introduction</h2>
<blockquote class="pullquote appear-right">
<p class="pullquote">
Bond: Vodka Martini.<br />
Bartender: Shaken or stirred?<br />
Bond: Do I look like I give a damn?
</p>
<p>
<cite>from <a href="http://www.imdb.com/title/tt0381061/">Casino Royale</a></cite>
</p>
</blockquote>
<p><a href="http://www.adaptivepath.com/ideas/essays/archives/000385.php">Ajax</a> functionality, i.e. loading and displaying new content to the user without having to refresh the page, is the new black these days (well, actually, it is the new black for quite a while already). A website without Ajax these days is like James Bond driving a <a href="http://www.toyota.com/">Toyota</a> (no offense to the Japanese automaker though)&mdash;it is just not right (at least a lot of product manager will make you believe that). So how are we going to deal with all that request/response hassle including browser incompatibilities without causing us headaches? We make YUIs Connection Manager do all the hard word for us! </p>
<h2>The Mission Statement</h2>
<p>What we would like to achieve is the following: </p>
<ul>
<li>We have <a href="http://www.klauskomenda.com/wp-content/uploads/2008/07/ayui_ms_step1.jpg">a page listing our 3 favorite James Bond actors</a></li>
<li>Without JavaScript, clicking on the link &#8220;[actor name] appeared in&#8230;&#8221; will takes us to <a href="http://www.klauskomenda.com/wp-content/uploads/2008/07/ayui_ms_step2.gif">a new page</a>, showing the actor again, with a table underneath listing movies he appeared in</li>
<li>With JavaScript, clicking on that link should keep the user <a href="http://www.klauskomenda.com/wp-content/uploads/2008/07/ayui_ms_step3.jpg">on the same page</a> and load that same table via Ajax from the server and display it below the images of the actors.</li>
</ul>
<h2>Step 1a: The Markup for the Overview Page</h2>
<p>As usual, we are not rushing into things, but instead stick to the initial plan of starting with the markup, adding appropriate CSS for styling and then add behavior using JavaScript on top. The markup bits for the list very straightforward:</p>
<pre><code >&lt;h1&gt;Which actor appeared in which (other) movies?&lt;/h1&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;img src="img/sean.jpg" alt="Sean Connery" /&gt;&lt;a href="Sean_Connery/"&gt;Sean Connery appeared in&amp;hellip;&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;img src="img/brosnan.jpg" alt="Pierce Brosnan" /&gt;&lt;a href="Pierce_Brosnan/"&gt;Pierce Brosnan appeared in&amp;hellip;&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;img src="img/craig.jpg" alt="Daniel Craig" /&gt;&lt;a href="Daniel_Craig/"&gt;Daniel Craig appeared in&amp;hellip;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</code></pre>
<p>This was easy and that first step can be viewed <a href="/wp-content/uploads/2008/07/ayui_m5_initial.html">on the initial demo page</a>.</p>
<h2>Step 1b: The Markup for the Details Page</h2>
<p>While we are at it, we can also prepare the markup for the page that gets loaded when a user clicks on one of the &#8220;&#8230;appeared in&#8230;&#8221; links:</p>
<pre><code >&lt;h1&gt;Sean Connery appeared in&amp;hellip;&lt;/h1&gt;
&lt;div&gt;
    &lt;img src="../img/sean.jpg" alt="Sean Connery" /&gt;
&lt;/div&gt;
&lt;!-- table will go here --&gt;</code></pre>
<h2>Step 1c: Setting up the Server</h2>
<p>Before we jump into Step 2, I would like to show you how I set up the server to support our Ajax functionality. I created sub directories for each actor which hold:</p>
<ul>
<li><a href="/wp-content/uploads/2008/07/Sean_Connery/index.php.txt">an index.php file</a></li>
<li><a href="/wp-content/uploads/2008/07/Sean_Connery/table_snippet.php.txt">a table_snippet.php file</a> which only contains the HTML fragment with the table to display (and which gets included in the index.php file)</li>
</ul>
<p>So the structure for the directory &#8220;Sean_Connery&#8221; might look like:</p>
<pre><code>Directory of \Sean_Connery

26.07.2008  21:59    &lt;DIR&gt;          .
26.07.2008  21:59    &lt;DIR&gt;          ..
23.07.2008  19:56             1.734 index.php
23.07.2008  20:46             6.932 table_snippet.php</code></pre>
<p>This is sufficient for this simple example, but in the real world, this would be set up differently. You would probably have one index.php file which, based on a querystring or particular part of the URL retrieves the data from a datasource, e.g. a database, generates the table markup and provides this to the browser. But going into these details goes beyond this tutorial. </p>
<p>How this kind of structure facilitates the Ajax flow will be explained when we get to Step 3.</p>
<h2>Step 2: Adding some styling</h2>
<p>As usual, we put some CSS into the game to make things a little bit prettier. No rocket science. The result can, again, be viewed <a href="/wp-content/uploads/2008/07/ayui_m5_step2_styles.html">on the demo page for this step</a>.</p>
<h2>Step 3: Ajax, please</h2>
<p>Now, when we click on one of the &#8220;&#8230;appeared in&#8230;&#8221; links we get redirected to a new page with the actor image at the top and the data table underneath. But now we want to use Ajax to keep the user on the same page, load the data and display it underneath our list of actors. How are we going to do it? </p>
<p>Before we dive into it, lets have a look at how <a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Connect.html">YAHOO.util.Connect</a> (the YUI Connection Manager) works. This object has a function as a property called asyncRequest:</p>
<pre><code>YAHOO.util.Connect.asyncRequest  ( method , uri , callback , postData )</code></pre>
<p>So what do these parameters do?</p>
<ul>
<li>method: either &#8220;GET&#8221; or &#8220;POST&#8221;</li>
<li>uri: the URI to your script that you request data from and that returns data to the script in your browser</li>
<li>callback: an object that defines which functions should handle the response coming back from the server</li>
<li>postData: additional data you want to send when doing a POST request</li>
</ul>
<p>We are only going to use the first 3 parameters in this example.</p>
<p>At first, we set up a skeleton for our JavaScript module at the bottom of the page and in the init function we get all the anchors on the page.</p>
<pre><code >&lt;!-- Dependency --&gt;
&lt;script src="http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js"&gt;&lt;/script&gt;

&lt;!-- Used for Custom Events and event listener bindings --&gt;
&lt;script src="http://yui.yahooapis.com/2.5.2/build/event/event-min.js"&gt;&lt;/script&gt;

&lt;!-- Source file --&gt;
&lt;script src="http://yui.yahooapis.com/2.5.2/build/connection/connection-min.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
YAHOO.namespace("AgentYUI");

YAHOO.AgentYUI.Mission5 = function () {

    var init = function () {
        // get all links on the page
        var anchors = document.getElementsByTagName("a");
        var len = anchors.length;
    };
    return {
        init: init
    };
}();

YAHOO.AgentYUI.Mission5.init();
&lt;/script&gt;</code></pre>
<p>After that, we loop through the anchors array and attach an event handler to every onclick event</p>
<pre><code>// loop through anchors and attach XHR request
for (var i = 0; i &lt; len; i++) {
    YAHOO.util.Event.addListener(anchors[i], "click", function (e) {
        YAHOO.util.Event.preventDefault(e);
        YAHOO.util.Connect.asyncRequest("GET", this.href + "table_snippet.php", { success: requestSuccess, failure: requestFailure });
        })
    };
}</code></pre>
<p>Within the loop, we are first using <a href="/archives/2007/10/14/agent-yui-mission-1-attaching-events-the-easy-way/">YAHOO.util.Event</a> to attach a listener. The event handler then first prevents the user from getting redirected to the non-JS page. And after that, we are using the newly introduced  YUI Connection Manager. We are doing a get request to <span class="code">this.href + &#8220;table_snippet.php&#8221;</span>, which will, at runtime, be resolved to e.g. &#8220;Sean_Connery/table_snippet.php&#8221;. If the Ajax request was successfull, we want to have a requestSuccess function that handles the response. If not, call requestFailure.</p>
<p>Now you can see that having one file, table_snippet.php, which serves the data for both the Ajax and non-Ajax version, is a good idea. It saves us from coding things twice when essentially, the data (and the markup) that we would like to serve are the same.</p>
<p>After that for-loop, we still need to do a tiny, but essential thing: We need to prepare a container where we want to put our HTML table when we get the response back. We do this by putting a div after our unordered list with <span class="code">id=container</span>:</p>
<pre><code>// create container where to put in the returned HTML
var bodyEl = document.getElementsByTagName("body")[0];
responseContainer = document.createElement("div");
bodyEl.appendChild(responseContainer);</code></pre>
<p>So what do the requestSuccess/requestFailure functions look like? They are both amazingly simple:</p>
<pre><code>var requestSuccess = function (o) {
    var response = o.responseText;
    responseContainer.innerHTML = response;
}

var requestFailure = function (o) {
    console.log("XHR failed!");
}</code></pre>
<p>In requestSuccess what happens is that a response object o gets passed in, which contains a lot of additional properties about the request/response (you can do a <span class="code">console.dir(o)</span> if you are interested into what sorts of info is contained in that object). For us, we really only care about <span class="code">responseText</span> because that contains the HTML of the table we want to display. All for us then is left to do is dump the markup we got from the server into our container element using <span class="code">innerHTML</span>. </p>
<p>Two notes regarding this:</p>
<ul>
<li>In the real world, you would probably deal with a response in JSON format more often than HTML fragments. To be able to use the response as a JSON object in your module, you need to eval it first. The syntax for this is:
<pre><code>var response = eval("(" + o.responseText + ")");</code></pre>
<p class="update">
<em>Update</em>: Strictly speaking, and for security reasons, it is safer to use the <a href="http://developer.yahoo.com/yui/json/">YUI JSON Utility</a> to take care of the parsing instead of using &#8220;eval&#8221;. We won&#8217;t go into details here, but <a href="http://www.jslint.com/lint.html">Douglas can explain why eval is evil</a>. So the syntax to use, when the JSON utility is included on the page (thanks <a href="#comment-8978">alfred</a> for pointing that out):
<pre><code>var response = YAHOO.lang.JSON.parse(o.responseText); </code></pre>
</p>
<p>After that you can access all the properties in the object that the server provided you in JSON format using the dot notation e.g. <span class="code">response.myProperty</span>.</li>
<li>People might argue that <span class="code">innerHTML</span> is bad. It is not. <a href="http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx">It is a proprietary method invented by Microsoft</a>t but it works in all major browsers today, which is the major thing here. Especially when dealing with HTML fragments in responses like this, it makes life much easier.</li>
</ul>
<p><a href="/wp-content/uploads/2008/07/ayui_m5_step3_request.html">Et voilá</a>, we have implemented our Ajax interaction.</p>
<p>Because we are not beginners anymore we can enhance the experience a little bit by using <a href="/archives/2008/01/28/agent-yui-mission-4-some-animation-q/">Animation</a>. After that little polishing, have a look at <a href="/wp-content/uploads/2008/07/ayui_m5_final.html">the final result</a>.</p>
<h2>Further Reading</h2>
<ul>
<li><a href="http://developer.yahoo.com/yui/connection/">YUI Connection Manager</a></li>
<li><a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Connect.html">YUI Connection Manager API documentation</a></li>
<li><a href="http://developer.yahoo.com/yui/examples/connection/index.html">Examples on YDN</a></li>
<li><a href="http://www.wrox.com/WileyCDA/Section/id-291408.html">Ajax and the Yahoo! Connection Manager</a> by <a href="http://www.nczonline.net/">Nicholas C. Zakas</a></li>
<li><a href="http://www.creativeui.com/2007/04/10/yui-part-ii/">Another Tutorial on the Connection Manage</a>r</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.klauskomenda.com/archives/2008/07/26/agent-yui-mission-5-ajax-shaken-not-stirred/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Agent YUI: Mission 4 &#8211; Some Animation, Q?</title>
		<link>http://www.klauskomenda.com/archives/2008/01/28/agent-yui-mission-4-some-animation-q/</link>
		<comments>http://www.klauskomenda.com/archives/2008/01/28/agent-yui-mission-4-some-animation-q/#comments</comments>
		<pubDate>Mon, 28 Jan 2008 01:22:57 +0000</pubDate>
		<dc:creator>Klaus</dc:creator>
				<category><![CDATA[Agent YUI]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://www.klauskomenda.com/archives/2008/01/28/agent-yui-mission-4-some-animation-q/</guid>
		<description><![CDATA[After dealing with the basic modules like DOM and Event during the last couple of Agent YUI tutorials, I am now moving on to the Animation module. Introduction All the cool moving, fading and more that you always wanted to put on your Web 2.0 site&#8230;piece of cake with YUI Animation. In this example, I [...]]]></description>
			<content:encoded><![CDATA[<p>After dealing with the basic modules like <a href="http://developer.yahoo.com/yui/dom/">DOM</a> and <a href="http://developer.yahoo.com/yui/event/">Event</a> during the <a href="/archives/2007/10/27/agent-yui-mission-2-magic-of-the-dom/">last</a> <a href="/archives/2007/12/02/agent-yui-mission-3-create-your-own-events/">couple</a> of Agent YUI tutorials, I am now moving on to the <a href="http://developer.yahoo.com/yui/animation/">Animation module</a>. <span id="more-126"></span></p>
<h2>Introduction</h2>
<p>All the cool moving, fading and more that you always wanted to put on your Web 2.0 site&#8230;piece of cake with YUI Animation. In this example, I am gonna show how to use <a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Anim.html">YAHOO.util.Anim</a> (for changing style properties of an element to create e.g. a sliding effect) and <a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Motion.html">YAHOO.util.Motion</a> (for moving an element around on the page).</p>
<h2>The Mission Statement</h2>
<p>We have 3 junks of information, each one related to a James Bond actor. Each junk consists of a picture of the actor, a headline and some additional biographical information. What we want to do is:</p>
<ul>
<li>Without JavaScript, all the items should be shown on the page on pageload and presented to the user (<a href="/wp-content/uploads/2008/01/ayui_m4_non_js.jpg">screenshot</a>).</li>
<li>With JavaScript, the image, as well as the headline should be &#8220;pulled in&#8221; from off the screen, one after the other. Finally, if the user requires more info about an actor, he can request that by clicking on &#8220;get more info&#8221; and the respective text will show using another animation effect (<a href="/wp-content/uploads/2008/01/ayui_m4_js.jpg">screenshot</a>).</li>
</ul>
<h2>Step 1: The Markup</h2>
<p>First, as with every other tutorial, we make sure that markup and styling are in place and then add behavior (JavaScript) an top. We start by putting the 3 junks of information on the page, marked up as list items. This would be the one for Sir Sean Connery:</p>
<pre><code >&lt;ul&gt;
    &lt;li id="connery"&gt;
       &lt;h2&gt;Sean Connery&lt;/h2&gt;
       &lt;a id="connery-get-more" href="http://en.wikipedia.org/wiki/Sean_Connery"&gt;Get more info&lt;/a&gt;
       &lt;img src="img/sean.jpg" alt="Sean Connery" /&gt;
       &lt;p&gt;Sean Connery (born 25 August 1930) is a retired Scottish actor and
       producer who is perhaps best known as...&lt;/p&gt;
    &lt;/li&gt;
    ...
&lt;/ul&gt;</code></pre>
<p>Please check out the <a href="/wp-content/uploads/2008/01/ayui_m4_initial.html">demo page for this first step</a>. For screenreaders and people viewing web pages with not that much CSS support, this is acceptable. But as we all know, bare-bones HTML looks ugly, so lets move on to Step 2.</p>
<h2>Step 2: Adding some styling</h2>
<p>In this step, we are creating the version of the site that should be displayed to users who have CSS support, but lack JavaScript for whatever reason. So we do our best to make the page look like we envisioned it and add some CSS styles to it. As this is about YUI and not about nifty CSS styling, I will not go into much detail at this point but simply let you, my dear reader, observe <a href="/wp-content/uploads/2008/01/ayui_m4_styles_added.html">the result</a> after Step 2 is completed. Still no JavaScript involved, folks.</p>
<h2>Step 3a: Animateify the list items</h2>
<p>Animateify &#8211; what an ugly word. Anyway. We start off putting in animation by including the required YUI files and declaring our module, including an empty <span class="code">init</span> function, and insert the call to the <span class="code">init</span> function, like this:</p>
<pre><code>&lt;script type="text/javascript" src="http://yui.yahooapis.com/2.3.1/build/yahoo-dom-event/yahoo-dom-event.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="http://yui.yahooapis.com/2.4.1/build/animation/animation-min.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;

YAHOO.namespace("AgentYUI");

YAHOO.AgentYUI.Mission4 = function () {
   var init = function () {

   };

   return {
      init: init
   }
}();

YAHOO.AgentYUI.Mission4.init();</code></pre>
<p>The first thing we want to do in the <span class="code">init</span> function is to put together references to the respective list items in an array and also store references to the text displayed for the respective actor: </p>
<pre><code>var items = [
    document.getElementById('connery'),
    document.getElementById('brosnan'),
    document.getElementById('craig')
];

conneryText = items[0].getElementsByTagName('p')[0];
brosnanText = items[1].getElementsByTagName('p')[0];
craigText = items[2].getElementsByTagName('p')[0];</code></pre>
<p>Now we can move on to animating the list items themselves. We want them to move in from offscreen, so what we need to do first, is add some JavaScript that actually positions the items offscreen. We do that in the head of the document (it looks ugly, but does the trick). We also add a couple of other styles that make sure that also the other items don&#8217;t appear up front (we want to animate them, remember?):</p>
<pre><code>&lt;script type="text/javascript"&gt;
document.write("&lt;style&gt;");
document.write("#connery, #brosnan, #craig { left: -500px }");
document.write("a { display: none } ");
document.write("h2 { width: 0; padding: 0 }");
document.write("p { height: 0 }");
&lt;/script&gt;</code></pre>
<p>After that, we can create a function called <span class="code">animateListItems</span> which will change the CSS properties of every item to move to 200px from the left on the screen. We do this with YAHOO.util.Motion, like:</p>
<pre><code>var animateListItems = function () {
    var duration = 1; /* setting the duration for the first animation */
    for (var i in items) {
        var listAnim = new YAHOO.util.Motion(items[i], {points:
            { to: [200, 0] } /* move every item to 200px left from the viewport edge */
        });

        listAnim.duration = duration++;
        listAnim.animate(); /* run animation */
    }
};</code></pre>
<p>What is going on? First we set a <span class="code">duration</span> variable to 1 &#8211; this is just an comfortable way to make the list items move in from offscreen one after the other. So the first one will take 1 second, the second one will take 2 seconds and the third one 3 seconds to move to its final position. We then loop through all the items and set the endpoint for every item to 200px from the left of the viewport on the x-axis. This is done for all 3 items subsequently. You can see the result of this step on <a href="/wp-content/uploads/2008/01/ayui_m4_li_animated.html">this demo page</a>.</p>
<h2>Step 3b: Animating the Headings</h2>
<p>Right after the image is in its place, the respective heading is supposed to appear &#8211; animated, of course. YAHOO.util.Anim has an Event <a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Anim.html#onComplete">onComplete</a> you can subscribe a function to which will be called when the animation is completed. So we add this to our <span class="code">animateListItems</span> function:</p>
<pre><code>var animateListItems = function () {
    ...
       listAnim.onComplete.subscribe(animateHeading); /* we use this hook to initiate the animation of the headline */
       listAnim.duration = duration++;
       listAnim.animate(); /* run animation */
    ...
};</code></pre>
<p>We will obviously use the function <span class="code">animateHeading</span> to make our headline(s) appear. In that function, we first set the CSS properties back to what was originally specified in the CSS:</p>
<pre><code>var actorItem = this.getEl(); // get original element, e.g. &lt;li id="connery"&gt;
var currentHeadline = actorItem.getElementsByTagName('h2')[0];
var currentGetMoreLink = actorItem.getElementsByTagName('a')[0];
YAHOO.util.Dom.setStyle(currentHeadline, "padding" , "5px" );
YAHOO.util.Dom.setStyle(currentGetMoreLink, "display" , "inline" );</code></pre>
<p>After that, we animate the heading. This time, we use YAHOO.util.Anim to animate a specific CSS property (the width in that case) to create the desired effect:</p>
<pre><code>var headAnim = new YAHOO.util.Anim(currentHeadline, {
    width: { to: 500 }
    },1, YAHOO.util.Easing.easeOut);</code></pre>
<p>What this does is it takes the headline of the list item currently dealt with and adjusts the width-property to 500px over a period of 1 second. In addition, we are adding a nice easing effect <img src='http://www.klauskomenda.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Thats all about the magic on this part and you can &#8211; of course &#8211; view <a href="/wp-content/uploads/2008/01/ayui_m4_h2_animated.html">a demo</a>.</p>
<h2>Step 3c: Making the text appear in a smooth way</h2>
<p>The final step is to nicely &#8220;slide in&#8221; the respective biographical text when the user clicks on &#8220;get more info&#8221;. So the first thing we need to do is attach Event listeners to every &#8220;get more info&#8221; link. So we add the following code to the <span class="code">init</span> function:</p>
<pre><code>/* attaching event listeners for "more info" links */
for (var i in items) {
    YAHOO.util.Event.addListener(items[i].getElementsByTagName('a')[0], 'click', animateText);
}</code></pre>
<p>As we would like to remember for each text if it is currently open or not (and a subsequent click on the link should make it disappear again), we need an object for each text. We already defined these in the <span class="code">init</span> function:</p>
<pre><code>conneryText = items[0].getElementsByTagName('p')[0];
brosnanText = items[1].getElementsByTagName('p')[0];
craigText = items[2].getElementsByTagName('p')[0];</code></pre>
<p>In the <span class="code">animateText</span> function we first need to check which of the links has been clicked. We determine which text we need to show by checking whether the id contains either &#8220;connery&#8221;, &#8220;brosnan&#8221; or &#8220;craig&#8221; and based on that, we show the respective text &#8211; again, animated <img src='http://www.klauskomenda.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  </p>
<pre><code>var targetEl = YAHOO.util.Event.getTarget(e);

if (targetEl.id.indexOf("connery")!= -1) {
    animEl = conneryText;
} else if (targetEl.id.indexOf("brosnan")!= -1) {
    animEl = brosnanText;
} else {
    animEl = craigText;
}</code></pre>
<p>We also add an additional property to the object (e.g. conneryText) so that we know if the text is currently expanded or hidden.</p>
<pre><code>if (animEl.isExpanded) {
    options = {
        height: { to: 0 }
    };
    animEl.isExpanded = false;
} else {
    options = {
        height: { to: 130 }
    };
    animEl.isExpanded = true;
}

var textAnim = new YAHOO.util.Anim(animEl, options ,1, YAHOO.util.Easing.easeOut);
textAnim.animate();</code></pre>
<p>And this is it. We managed to animate the image, the headline and the text and also made sure that there is an appropriate version for non-JavaScript (and non-CSS users) in place. Lets have a look at <a href="/wp-content/uploads/2008/01/ayui_m4_final.html">the final result</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.klauskomenda.com/archives/2008/01/28/agent-yui-mission-4-some-animation-q/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Agent YUI: Mission 3 &#8211; Create Your Own Events</title>
		<link>http://www.klauskomenda.com/archives/2007/12/02/agent-yui-mission-3-create-your-own-events/</link>
		<comments>http://www.klauskomenda.com/archives/2007/12/02/agent-yui-mission-3-create-your-own-events/#comments</comments>
		<pubDate>Sun, 02 Dec 2007 18:57:05 +0000</pubDate>
		<dc:creator>Klaus</dc:creator>
				<category><![CDATA[Agent YUI]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://www.klauskomenda.com/archives/2007/12/02/agent-yui-mission-3-create-your-own-events/</guid>
		<description><![CDATA[In the first part of this tutorial series, we were talking about a very straight forward way of attaching events to elements in the DOM. This article will tell you how to even create our own Custom Events and trigger them. This is what the YUI guys call an &#8220;interesting moment&#8221; in your application. Introduction [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="/archives/2007/10/14/agent-yui-mission-1-attaching-events-the-easy-way/">the first part of this tutorial series</a>, we were talking about a very straight forward way of attaching events to elements in the DOM. This article will tell you how to even create our own <a href="http://developer.yahoo.com/yui/event/#customevent">Custom Events</a> and trigger them. This is what the YUI guys call an &#8220;interesting moment&#8221; in your application.<span id="more-118"></span></p>
<h3>Introduction</h3>
<p>The DOM offers various <a href="http://www.quirksmode.org/js/events_compinfo.html#mouse">Events</a> that you can listen and attach a function to, e.g. onclick, onmouseover. But sometimes, these might offer you not enough functionality in your own web application. With YAHOO.util.CustomEvent, you are able to create your own Custom Events, which can be described as an &#8220;interesting moment&#8221; within the flow of your application. If that &#8220;interesting moment&#8221; happens, you can fire (i.e. trigger) that event and run a function which is &#8220;subscribed&#8221; to this event. A checklist of creating a simple Custom Event could read as follows:</p>
<ol>
<li>Create a Custom Event Object in your code (using YAHOO.util.CustomEvent)</li>
<li>Declare a function that should get executed when this &#8220;interesting moment&#8221; happens</li>
<li>&#8220;Subscribe&#8221; this function to the Custom Event (which will be called when the event gets fired)</li>
</ol>
<p>The following exercise will show you how to create a Custom Event and trigger it when a certain condition within the code is met.</p>
<h3>The Mission Statement</h3>
<p>We have a blurred version of a picture which shows a very famous James Bond actor (<a href="/wp-content/uploads/2007/12/ayui_m3_step1.jpg">step 1</a>). The picture is split into 9 parts and when clicking on one of them, the clear (i.e. unblurred) version gets displayed (<a href="/wp-content/uploads/2007/12/ayui_m3_step2.jpg">step 2</a>). When all parts of the in-focus picture are available, a speech bubble should be displayed at the position of the mouse cursor (<a href="/wp-content/uploads/2007/12/ayui_m3_step3.jpg">step 3</a>). Inside the speech bubble, a random James Bond movie quote should be displayed. </p>
<h3>The Plan</h3>
<p>Based on this information, we can make a step-by-step plan of what is supposed to happen and how we are going to do it:</p>
<ol>
<li>When the page gets loaded, the user will see the blurred version of the image (made up of an unordered list)</li>
<li>We will attach an onclick event to the ul which captures mouseclicks within the list</li>
<li>If the user clicks on the image (i.e. on one of the 9 parts) we will replace the respective part with the focused version</li>
<li>When the last image is swapped, we will trigger a Custom Event (this is our &#8220;interesting moment&#8221;)</li>
<li>This Custom Event caters for the display of a speech bubble, with a random James Bond movie quote, at the last mouse cursor position</li>
</ol>
<h3>The Implementation</h3>
<p><a href="/wp-content/uploads/2007/12/ayui_m3_initial.html">The first steps</a> involve creating the HTML markup and adding some styling rules. As tables are evil, we will use an ul to put the 9 image parts together. Unfortunately, we need to introduce a little hack to remove the little horizontal gaps which will otherwise get displayed in the browser:</p>
<pre><code>#container li {
    float: left;
    list-style: none;
    font-size: 0; // needed to get rid of gaps between rows
}</code></pre>
<p><a href="/wp-content/uploads/2007/12/ayui_m3_imgswap.html">Step two</a> is implementing the image swap function. This will be triggered by an onclick Event attached to the unordered list. We can attach it to the ul, because through <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-bubbling">Event bubbling</a> the parent element will capture any events the are triggered by it&#8217;s child elements. The function <span class="code">imgSwap()</span> will then replace the <span class="code">src</span> attribute of the image with the one in focus. </p>
<p>We also need to know which image has been clicked and when all 9 images got replaced. Because of that, we will get all the img elements on the page, loop through them and put each of them into an array. We will need an array, because JavaScript offers a nice function called <span class="code">splice()</span> which lets you remove elements from an array (but not from an object). Therefore: get all the images (which returns an object with all the images) and feed them into array.</p>
<pre><code>var init = function () {
    // attach event to whole unordered list
    var imgContainerEl = YAHOO.util.Dom.get("container");
    YAHOO.util.Event.addListener(imgContainerEl, "click", imgSwap);

    // get all image elements
    tmp = document.getElementsByTagName("img");
    imgArrayLength = tmp.length;

    // unfortunately, tmp is an object (not an array)
    // we need to therefor put all the items into an array in order
    // to use splice() to remove an item when it gets clicked
    imgArray = [];
    for (var i = 0; i &lt; imgArrayLength; i++) {
        imgArray.push(tmp[i]); // move elements from object into array
    }
};</code></pre>
<p><span class="code">imgSwap()</span> then caters for the actual replacement of the image. It uses <span class="code">YAHOO.util.Event.getTarget(e)</span> to retrieve the target of the onclick event (which, in our case, will be one of the 9 image elements). It will then check if the <span class="code">src</span> attribute will contain &#8220;blur_&#8221; and replace it with an empty string. Conveniently, I named to images in a way that this works (e.g. blurred: connery_blur_01.gif, unblurred: connery_01.gif). Using <span class="code">splice()</span> it is then possible to remove that respective image from the array which holds all the images on the page. With every click, the length of that array decreases until it is empty, which tells us that all 9 images got swapped and our Custom Event should be triggered.</p>
<pre><code>var imgSwap = function (e) {
    var imgEl = YAHOO.util.Event.getTarget(e);

    if (imgEl.src.indexOf("blur") !== -1) {
        // on click on image swap background image to unblurred version
        var oldSrc = imgEl.src;
        var newSrc = oldSrc.replace("blur_", "");
        imgEl.src = newSrc;

        for (var i = 0; i &lt; imgArrayLength; i++) {
            // loop through array which holds all images on page
            if (imgArray[i].src.indexOf(newSrc) !== -1) {
                // find the one which just got clicked and remove it from array
                imgArray.splice(i, 1);
                imgArrayLength = imgArray.length; // adjust length of array
            }
        }
    }
};</code></pre>
<p>Now it is time for creating our Custom Event. At the beginning of our module code, we will therefor create new Custom Event Object like this:</p>
<pre><code>var onAllClicked = new YAHOO.util.CustomEvent("allClicked");</code></pre>
<p>When creating the new object, you can pass in a parameter which will be the type of the event. This is basically your own custom name for this special event and can be used to trigger different behavior.<br />
In our <span class="code">init()</span> function, we will then subscribe a function to this Custom Event:</p>
<pre><code>onAllClicked.subscribe(showQuotesBubble);</code></pre>
<p>This means basically: &#8220;When the Custom Event &#8216;allClicked&#8217; gets triggered, call the function &#8216;showQuotesBubble&#8217;&#8221;. Now all we need to do is fire the event at the right moment. This moment is exactly when the image array is empty. <a href="/wp-content/uploads/2007/12/ayui_m3_custom.html">In the example</a>, the <span class="code">showQuotesBubble</span> function does nothing else but alerting a string.</p>
<pre><code>if (imgArrayLength &lt; 1) {
    onAllClicked.fire();
}</code></pre>
<p>Now the major parts are done. When examining the example, you have probably noticed that the function which is subscribed to the Custom Event takes two arguments, <span class="code">type</span> and <span class="code">args</span>. <span class="code">type</span> is basically the event type you can state when creating the object (&#8220;allClicked&#8221; in our case) and <span class="code">args</span> is just an array of arguments passed into the array. We will use this functionality to pass in the coordinates of the mouse cursor when the last image gets clicked:</p>
<pre><code>onAllClicked.fire({x: e.clientX, y: e.clientY});</code></pre>
<p>As far as Custom Events go, this example is basically finished. All that is left is create a new element in the DOM (a <span class="code">blockquote </span> which holds a random James Bond quote) and use the X/Y values to display that element at these coordinates. You can take a look at the <a href="/wp-content/uploads/2007/12/ayui_m3_final.html">final result</a> with the finishing touches applied. </p>
<h3>Further reading</h3>
<ul>
<li><a href="http://developer.yahoo.com/yui/event/#customevent">YUI: Event Utility: Using Custom Events</a></li>
<li><a href="http://developer.yahoo.com/yui/examples/event/custom-event.html">A basic example</a> using Custom Objects on the YUI site</li>
<li><a href="http://www.quirksmode.org/">PPK</a> on <a href="http://www.quirksmode.org/js/events_order.html">Event bubbling</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.klauskomenda.com/archives/2007/12/02/agent-yui-mission-3-create-your-own-events/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Agent YUI: Mission 2 &#8211; Magic Of The DOM</title>
		<link>http://www.klauskomenda.com/archives/2007/10/27/agent-yui-mission-2-magic-of-the-dom/</link>
		<comments>http://www.klauskomenda.com/archives/2007/10/27/agent-yui-mission-2-magic-of-the-dom/#comments</comments>
		<pubDate>Sat, 27 Oct 2007 13:50:38 +0000</pubDate>
		<dc:creator>Klaus</dc:creator>
				<category><![CDATA[Agent YUI]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://www.klauskomenda.com/archives/2007/10/27/agent-yui-mission-2-magic-of-the-dom/</guid>
		<description><![CDATA[The last article in the Agent YUI series was about YAHOO.util.Event, one of the YUI core components. The other, probably even more used component is YAHOO.util.Dom, which provides helper functions for several DOM related tasks. So our mission today will be checking out these functions a little bit further. Introduction As you can see from [...]]]></description>
			<content:encoded><![CDATA[<p>The last article in the Agent YUI series was about <a href="http://developer.yahoo.com/yui/event/">YAHOO.util.Event</a>, one of the YUI core components. The other, probably even more used component is <a href="http://developer.yahoo.com/yui/dom/">YAHOO.util.Dom</a>, which provides helper functions for several DOM related tasks. So our mission today will be checking out these functions a little bit further.<span id="more-115"></span></p>
<h3>Introduction</h3>
<p>As you can see from the <a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Dom.html">API documentation for the DOM component</a>, it provides several functions which can become quite handy and enhances the standard DOM functionality, e.g.:</p>
<ul>
<li><a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Dom.html#addClass">addClass</a>: add a CSS class to any given element</li>
<li><a href="http://http://developer.yahoo.com/yui/docs/YAHOO.util.Dom.html#removeClass">removeClass</a>: removes a CSS class from an element</li>
<li><a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Dom.html#get">get</a>: get any given element from the DOM</li>
<li><a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Dom.html#getElementsByClassName">getElementsByClassName</a>: as the name implies, retrieving elements based on their classname</li>
<li><a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Dom.html#getStyle">getStyle</a>: get a style property from an element</li>
<li><a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Dom.html#setStyle">setStyle</a>: set a particular style property</li>
<li><a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Dom.html#insertAfter">insertAfter</a>: a long awaited functionality that lets you insert a element after a given element in the DOM tree</li>
</ul>
<p>But there are many more useful functions that can be found in the <a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Dom.html">API documentation of this component</a>.</p>
<h3>The Mission Statement</h3>
<p>The following little example deals with this task: A given text contains several anchor elements, most of them point to pages on <a href="http://en.wikipedia.org/wiki/Main_Page">Wikipedia</a>, some of them are just external links and only one is a local link. They should be marked as follows:</p>
<ul>
<li>Marking <a style="padding-left: 20px; background: #fff url(/wp-content/uploads/2007/10/ayui_m2/img/wikipedia-icon.gif) top left no-repeat;" href="http://en.wikipedia.org/">a link to wikipedia</a></li>
<li>Marking <a style="padding-left: 16px; background: #fff url(/wp-content/uploads/2007/10/ayui_m2/img/icon_external_link.gif) top left no-repeat;"href="http://orf.at/">a link to any other external resource</a></li>
</ul>
<p>Due to the fact that Internet Explorer 6 and below do not support the CSS attribute selector, it is a bit difficult to accomplish this task (and make it work in IE6) by using HTML and CSS only. But with the help of JavaScript and the <a href="http://developer.yahoo.com/yui/">YUI</a>, it is &#8211; really &#8211;  a piece of cake. </p>
<h3>The Plan</h3>
<p>For the sake of simplicity, we imagine the following:</p>
<p>   1. JavaScript is available: search for all anchors on the page and based on the href, attach a certain class<br />
   2. JavaScript is not available: leave it with standard link styling</p>
<h3>The Implementation</h3>
<blockquote class="pullquote appear-left">
<p class="pullquote">
Bond: Who would want to put a contract out on me?<br />
M: Jealous husbands, humiliated tailors, outraged chefs. The list is endless!
</p>
<p>
<cite>from <a href="http://imdb.com/title/tt0071807/">The Man with the Golden Gun</a></cite>
</p>
</blockquote>
<p>We start off with a little text kindly provided by Wikipedia, with some introduction about <a href="http://en.wikipedia.org/wiki/James_Bond">James Bond</a>. You might want to check out <a href="/wp-content/uploads/2007/10/ayui_m2/ayui_m2_initial.html">the initial file</a>. Even this short text already includes several anchor elements, most of them pointing to other resources on Wikipedia. However, the links in the references list point to pages which can be found elsewhere on the web. Finally, a little note at the end leads the user to the starting point of the <a href="/archives/2007/10/13/agent-yui-introduction/">Agent YUI series</a>. </p>
<p>Before we dive into the JavaScript, we add 2 classes to our styles which will cater for the different styling of our links:</p>
<pre>
<code>a.wp-link {
    padding-left: 20px;
    background: #fff url(img/wikipedia-icon.gif) top left no-repeat;
}

a.local-link {
    padding-left: 16px;
    background: #fff url(img/icon_external_link.gif) top left no-repeat;
}</code>
</pre>
<p>Then we create our JavaScript module for this exercise:</p>
<pre>
<code >YAHOO.AgentYUI.Mission2 = function () {
    // our javascript code will go in here
}();</code>
</pre>
<p>We then define an <span class="code">init</span> function which will scan through the page and get all the anchor elements. Luckily, there is <a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Dom.html#getElementsBy">YAHOO.util.Dom.getElementsBy</a> which will get all the anchor elements on the page and feed them into a method (which we will define shortly) which checks the <span class="code">href</span> attribute:</p>
<pre>
<code>var init = function () {
    // get all anchors on the page and feed them to the testing method
    YAHOO.util.Dom.getElementsBy(formatLinks, "a");
};</code>
</pre>
<p>Our testing method <span class="code">formatLinks</span> is then taking one element of the anchors array at a time. It checks the <span class="code">href</span> attribute and based on that will attach a new class using <a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Dom.html#addClass">YAHOO.util.Dom.addClass</a>:</p>
<pre>
<code>var formatLinks = function (el) {
    var currentHref = el.getAttribute("href");

    if (currentHref.indexOf("http://en.wikipedia.org") !== -1) {
        YAHOO.util.Dom.addClass(el, "wp-link");
    } else if (currentHref.indexOf("http://") !== -1) {
        YAHOO.util.Dom.addClass(el, "local-link");
    }
};</code>
</pre>
<p>After some cleaning up and making the code a little bit more structured, we get our <a href="/wp-content/uploads/2007/10/ayui_m2/ayui_m2_final.html">final result</a>. As stated above, this is just a little example of what can be accomplished using the YUI DOM component which provides loads of functions that can support developers when dealing with DOM related tasks and to make the functionality work cross browser. </p>
<p>For further information how the DOM component can assist you, please check out the reading resources listed below.</p>
<h3>Further Reading</h3>
<ul>
<li><a href="http://developer.yahoo.com/yui/">YUI Library</a></li>
<li><a href="http://developer.yahoo.com/yui/dom/">DOM Component</a></li>
<li><a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Dom.html">DOM Component API documentation</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.klauskomenda.com/archives/2007/10/27/agent-yui-mission-2-magic-of-the-dom/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Agent YUI: Mission 1 &#8211; Attaching Events (the easy way)</title>
		<link>http://www.klauskomenda.com/archives/2007/10/14/agent-yui-mission-1-attaching-events-the-easy-way/</link>
		<comments>http://www.klauskomenda.com/archives/2007/10/14/agent-yui-mission-1-attaching-events-the-easy-way/#comments</comments>
		<pubDate>Sun, 14 Oct 2007 13:53:47 +0000</pubDate>
		<dc:creator>Klaus</dc:creator>
				<category><![CDATA[Agent YUI]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://www.klauskomenda.com/archives/2007/10/14/agent-yui-mission-1-attaching-events-the-easy-way/</guid>
		<description><![CDATA[This entry is part of the Agent YUI tutorial series. This time, the topic is all about attaching events to an object in the DOM using the Event component from YUI. The Mission Statement In this simple example we would like to accomplish the following: We have a link on the page which will lead [...]]]></description>
			<content:encoded><![CDATA[<p>This entry is part of the <a href="/archives/2007/10/13/agent-yui-introduction/">Agent YUI tutorial series</a>. This time, the topic is all about attaching events to an object in the DOM using the Event component from <a href="http://developer.yahoo.com/yui/">YUI</a>.<span id="more-113"></span></p>
<h3>The Mission Statement</h3>
<p>In this simple example we would like to accomplish the following: We have a link on the page which will lead the user to a page with a list of photos (the non-JavaScript version). If JavaScript is enabled, users should stay on the page and out of the pool of images, one should be randomly displayed on click on the link.</p>
<h3>The Plan</h3>
<p>So we have 2 different scenarios:</p>
<ol>
<li>JavaScript is available: randomly display an image from the pool</li>
<li>JavaScript is not available: lead user to a page with all the images</li>
</ol>
<h3>The Implementation</h3>
<p>The HTML markup we are starting with looks like this (and you can also check it in the <a href="/wp-content/uploads/2007/10/ayui_m1/ayui_m1_initial.html">initial file</a>):</p>
<pre>
<code >&lt;a href="all.html" id="switch"&gt;Show me more, James&lt;/a&gt;
&lt;img src="daniel_craig.jpg" alt="James Bond Picture" id="picture" /&gt;</code>
</pre>
<p>We will only make use of the YUI Core components, so all we need to include is the <span class="code">yahoo-dom-event.js</span> file from the recent YUI build. </p>
<pre>
<code>&lt;script type="text/javascript"
src="http://yui.yahooapis.com/2.3.1/build/yahoo-dom-event/yahoo-dom-event.js"&gt;&lt;/script&gt; </code>
</pre>
<p>After that, we need to create our main object, which we will use to wrap around our functions:</p>
<pre>
<code>YAHOO.namespace("AgentYUI");</code>
</pre>
<p>As this is the our first mission, we will define our module like this:</p>
<pre>
<code>YAHOO.AgentYUI.Mission1 = function () {}();</code>
</pre>
<p>Lets define the function that does the image swap first. What this function needs to do is quite simple. Out of an array of image names, get one of them on random and assign this value to the src attribute of the image element. That is fairly easy:</p>
<pre>
<code>var switchImage = function () {
    var imageEl = YAHOO.util.Dom.get("picture");
    var images = ['daniel_craig.jpg', 'pierce_brosnan.jpg', 'sean_connery.jpg'];
    imageEl.src ="img/" + images[Math.round(Math.random() * 2)];
};</code>
</pre>
<h3>What happens here?</h3>
<blockquote class="pullquote appear-left">
<p class="pullquote">
Blofeld: The satellite is now over&#8230; Kansas. Well, if we blow up Kansas the world may not hear about it for years.
</p>
<p>
<cite>from <a href="http://www.imdb.com/title/tt0066995/">Diamonds Are Forever</a></cite>
</p></blockquote>
<p><a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Dom.html#get">YAHOO.util.Dom.get(&#8220;picture&#8221;)</a> returns a reference to the HTML object on the page with the id &#8220;picture&#8221;. The other lines of code are basically defining the array of image names and then picking one of the array items on random (this is done by creating a random number between 0 and 1 and multiplying it by 2). </p>
<p>Now it is time to bring the <a href="http://developer.yahoo.com/yui/event/">Event Component</a> into the game. We need some kind of initialitzation (or main) method to run that attaches our event to the anchor. In this init method, we make use of <a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Event.html">YAHOO.util.Event</a>, to attach the behavior, like so: </p>
<pre>
<code>var init = function () {
    // attach event to anchor
    YAHOO.util.Event.addListener("switch", "click", switchImage);
};</code>
</pre>
<h3>What happens here?</h3>
<p><a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Event.html#addListener">YAHOO.util.Event.addListener</a> gets the element with the ID &#8220;switch&#8221; and attaches an &#8220;onclick&#8221; event. If that event is fired, <span class="code">switchImage</span> gets executed.</p>
<p>With a little tidying up and proper use of the revealing module pattern, we get a <a href="/wp-content/uploads/2007/10/ayui_m1/ayui_m1_almost.html">result</a> we can almost be happy with. But it seems as if the image gets changed and then the browser redirects to the page specified in the href attribute. For non-JavaScript users, that would be fine, but if JavaScript is enabled, that redirect should not happen. YUI provides a nice function, which lets you prevent that, called <a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Event.html#preventDefault">preventDefault</a>. We will add that to our <span class="code">switchImage</span> function like so:</p>
<pre>
<code>var switchImage = function (e) {
    YAHOO.util.Event.preventDefault(e);
    var imageEl = YAHOO.util.Dom.get(config.imageId);
    imageEl.src = config.imageFolder + "/" + config.images[Math.round(Math.random() * 2)];
};</code>
</pre>
<p>What happens is: <span class="code">e</span> is the event object that gets passed into the function automatically by the YUI. With that object at hand, we can use <span class="code">YAHOO.util.Event.preventDefault</span> to prevent the browser from redirecting to the next page. So we did it. Take a look at the <a href="/wp-content/uploads/2007/10/ayui_m1/ayui_m1_final.html">final result</a>.</p>
<h3>Further Reading</h3>
<ul>
<li><a href="http://developer.yahoo.com/yui/">YUI Library</a></li>
<li><a href="http://developer.yahoo.com/yui/event/">Event Component</a></li>
<li><a href="http://developer.yahoo.com/yui/dom/">DOM Component</a></li>
<li><a href="http://developer.yahoo.com/yui/docs/">API documentation</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.klauskomenda.com/archives/2007/10/14/agent-yui-mission-1-attaching-events-the-easy-way/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Agent YUI: Introduction</title>
		<link>http://www.klauskomenda.com/archives/2007/10/13/agent-yui-introduction/</link>
		<comments>http://www.klauskomenda.com/archives/2007/10/13/agent-yui-introduction/#comments</comments>
		<pubDate>Sat, 13 Oct 2007 13:54:03 +0000</pubDate>
		<dc:creator>Klaus</dc:creator>
				<category><![CDATA[Agent YUI]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://www.klauskomenda.com/archives/2007/10/14/agent-yui-introduction/</guid>
		<description><![CDATA[This is gonna be a series for all Web Developers among you, my fellow readers. And all your movie lovers (maybe). Cause it is going to feature some quotes from the most famous spy in movie history. But what it really is: a series of tutorials how the Yahoo! User Interface Library (YUI) can be [...]]]></description>
			<content:encoded><![CDATA[<p>This is gonna be a series for all Web Developers among you, my fellow readers. And all your movie lovers (maybe). Cause it is going to feature some quotes from the most famous spy in movie history. But what it really is: a series of tutorials how the <a href="http://developer.yahoo.com/yui/">Yahoo! User Interface Library (YUI)</a> can be your secret weapon for many Web Development matters.<span id="more-114"></span></p>
<h3>Introduction</h3>
<blockquote class="appear-right pullquote"><p class="pullquote">Bond: You know, you&#8217;re cleverer than you look!<br />
Q: Hmm&#8230; still, better than looking cleverer than you are.</p>
<p><cite>from <a href="http://www.imdb.com/title/tt0246460/">Die Another Day</a></cite></p>
</blockquote>
<p>The YUI is a JavaScript library created and maintained by the <a href="http://developer.yahoo.com/">Yahoo! Developer Network</a>. It consists of several components which make the life of Web Developers easier in a way that common desired functionality can easily be achieved by using one (or more) of the components provided by YUI. As with other JavaScript libraries, it aims towards cross-browser compatibility and giving the user the possibility to use one function/component, and does not have to worry if it works in browser X &#8211; the library takes care of that.</p>
<p>Apart from JavaScript components to re-use, YUI also includes several CSS resources &#8211; for example, to apply a common ground by resetting all the default browser margins, paddings etc. </p>
<h3>Why YUI? Why not library X?</h3>
<p>From my personal point of view, there are several reasons for using YUI:</p>
<ol>
<li>Unlike some other libraries, the YUI library consists of several single JavaScript files which can be included in a webpage separately. The library does not force you to include one single file, whichs size might amount to 100kB (or more), which increases page load times.</li>
<li>YUI is maintained by <a href="http://www.yahoo.com/">Yahoo!</a>, a big player in the internet industry, which increases the likelihood of continued support for and development on that library.</li>
<li>The syntax is easy to understand. It might be more verbose than the syntax of other libraries (e.g. <a href="http://jquery.com/">jQuery</a>), but I believe it is much more easier to hand over code from one developer to another, even if that person has not worked with YUI before.</li>
</ol>
<h3>Components</h3>
<p>As stated above, YUI consists of several components. In the current version (2.3.1 as of October 14th, 2007), the following components come with it and are considered stable to use:</p>
<h4>YUI Core</h4>
<ul>
<li><a href="http://developer.yahoo.com/yui/yahoo/">YAHOO Global Object</a>: provides a single global namespaces for all components</li>
<li><a href="http://developer.yahoo.com/yui/dom/">Dom</a>: used for common DOM tasks</li>
<li><a href="http://developer.yahoo.com/yui/event/">Event</a>: comprises methods related to attaching and subscribing to events</li>
</ul>
<h4>YUI Library Utilities</h4>
<ul>
<li><a href="http://developer.yahoo.com/yui/animation/">Animation</a>: animate elements involving size, opacity, color, position, and other visual characteristics</li>
<li><a href="http://developer.yahoo.com/yui/connection/">Connection Manager</a>: simplifies XMLHttpRequests &#8211; if you love AJAX, this will be your friend</li>
<li><a href="http://developer.yahoo.com/yui/dragdrop/">Drag &#038; Drop</a>: create a draggable interface efficiently</li>
</ul>
<h4>YUI Library Controls/Widgets</h4>
<ul>
<li><a href="http://developer.yahoo.com/yui/autocomplete/">AutoComplete</a>: provides suggestion and completion functionality for text input (aka &#8220;Suggest as you type&#8221;)</li>
<li><a href="http://developer.yahoo.com/yui/calendar/">Calendar</a>: calendar interface entirely created with JavaScript</li>
<li><a href="http://developer.yahoo.com/yui/container/">Container</a>: family of components to let developers create content-containing modules (it includes <a href="http://developer.yahoo.com/yui/container/module/index.html">Module</a> and <a href="http://developer.yahoo.com/yui/container/overlay/index.html">Overlay</a>: <a href="http://developer.yahoo.com/yui/container/tooltip/index.html">Tooltip</a>, <a href="http://developer.yahoo.com/yui/container/panel/index.html">Panel</a>, <a href="dialog/index.html">Dialog</a>, and <a href="http://developer.yahoo.com/yui/container/simpledialog/index.html">SimpleDialog</a>)</li>
<li><a href="http://developer.yahoo.com/yui/menu/">Menu</a>: as the name implies&#8230;makes it easier to add and display menus</li>
<li><a href="http://developer.yahoo.com/yui/slider/">Slider</a>: enables the user to adjust values in a finite range along one or two axes</li>
<li><a href="http://developer.yahoo.com/yui/tabview/">TabView</a>: is designed to enable developers to create navigable tabbed views of content</li>
<li><a href="http://developer.yahoo.com/yui/treeview/">TreeView</a>: create a visual presentation of hierarchical node data</li>
</ul>
<h4>YUI Library CSS Tools</h4>
<ul>
<li><a href="http://developer.yahoo.com/yui/reset/">CSS Reset</a>: neutralizes browser CSS styles</li>
<li><a href="http://developer.yahoo.com/yui/base/">CSS Base</a>: applies consistent style foundation for common elements</li>
<li><a href="http://developer.yahoo.com/yui/fonts/">CSS Fonts</a>: foundation for typography and font-sizing</li>
<li><a href="http://developer.yahoo.com/yui/grids/">CSS Grids</a>: more than 1,000 CSS-driven wireframes in a 4KB file</li>
</ul>
<p>The following components are considered <a href="http://developer.yahoo.com/yui/articles/faq/#beta">beta</a>:</p>
<ul>
<li><a href="http://developer.yahoo.com/yui/history/">Browser History Manager</a>: &#8230;designed to facilitate the creation of web applications in which the navigation buttons are fully functional</li>
<li><a href="http://developer.yahoo.com/yui/datasource/">DataSource</a>: provides a common configurable interface for other components to interact with different types of data</li>
<li><a href="http://developer.yahoo.com/yui/element/">Element Utility</a>: makes simpler common tasks such as adding listeners, manipulating the DOM, and setting and getting attributes</li>
<li><a href="http://developer.yahoo.com/yui/imageloader/">ImageLoader Utility</a>: allows you as an implementer to delay the loading of images on your web page until such a time as the your user is likely to see them</li>
<li><a href="http://developer.yahoo.com/yui/yuiloader/">YUILoader Utility</a>: allows you to load specific YUI components and their dependencies into your page via script</li>
<li><a href="http://developer.yahoo.com/yui/yuitest/">YUI Test</a>: testing framework for browser-based JavaScript solutions</li>
<li><a href="http://developer.yahoo.com/yui/button/">Button</a>: enables the creation of rich, graphical buttons that function like traditional HTML form buttons</li>
<li><a href="http://developer.yahoo.com/yui/colorpicker/">Color Picker Control</a>: provides a rich visual interface for color selection</li>
<li><a href="http://developer.yahoo.com/yui/datatable/">DataTable</a>: provides a simple yet powerful API to display screen-reader accessible tabular data on a web page</li>
<li><a href="http://developer.yahoo.com/yui/editor/">Rich Text Editor</a>: replaces a standard HTML textarea &#8211; it allows for the rich formatting of text content</li>
</ul>
<p>This series is meant to help newcomers to get started with the YUI library by providing some simple examples (starting with the core components and taking it from there). The first one will be <a href="/archives/2007/10/14/agent-yui-mission-1-attaching-events-the-easy-way/">Mission 1: Attaching Events (the easy way)</a>.</p>
<h3>How to include and use YUI components</h3>
<p>To make use of the powerful YUI library, the required component files need to be included in a script statement on the page. If you only want to make use of the core components (YAHOO, Event, DOM), the include statements should look like this:</p>
<pre>
<code >&lt;!-- Dependency --&gt;
&lt;script type="text/javascript"
src="http://yui.yahooapis.com/2.3.1/build/yahoo/yahoo-min.js"&gt;&lt;/script&gt;
&lt;!-- Event source file --&gt;
&lt;script type="text/javascript"
src="http://yui.yahooapis.com/2.3.1/build/event/event-min.js"&gt;&lt;/script&gt;
&lt;!-- Dom source file --&gt;
&lt;script type="text/javascript"
src="http://yui.yahooapis.com/2.3.1/build/dom/dom-min.js"&gt;&lt;/script&gt;</code>
</pre>
<p>Or even shorter:</p>
<pre>
<code>&lt;script type="text/javascript"
src="http://yui.yahooapis.com/2.3.1/build/yahoo-dom-event/yahoo-dom-event.js"&gt;&lt;/script&gt; </code>
</pre>
<p>The &#8220;-min&#8221; addition to the JavaScript file tells you that this file is a minified version of the original source file. This means, comments, carriage returns and other unnecessary whitespace have been removed from the file to reduce filesize and save bandwidth. </p>
<p>Just before the closing body tag, those JavaScript files should get included in the page. <a href="http://crockford.com/">Douglas Crockford</a> can tell you <a href="http://javascript.crockford.com/code.html">why it is a good idea to include JavaScript there</a> instead of in the head. It is also part of <a href="http://developer.yahoo.com/performance/rules.html#js_bottom">Yahoo!&#8217;s Exceptional Performance Rules</a>.</p>
<p>One word regarding the examples to come during this series: I am going to use the <a href="http://www.wait-till-i.com/index.php?p=476">Revealing Module Pattern</a> (courtesy of <a href="http://www.wait-till-i.com/">Christian Heilmann</a>) to write the example-specific JavaScript code. Should you need help to understand how this pattern works, take a look at Christian&#8217;s post or check out my article on <a href="/code/javascript-programming-patterns/">JavaScript Programming Patterns</a>. Hope you find that stuff useful!</p>
<p>The first part of the series: <a href="/archives/2007/10/14/agent-yui-mission-1-attaching-events-the-easy-way/">Mission 1: Attaching Events (the easy way)</a></p>
<h3>Resources</h3>
<ul>
<li><a href="http://developer.yahoo.com/yui/">The Yahoo! User Interface Library (YUI)</a></li>
<li><a href="http://yuiblog.com/">Yahoo! User Interface Blog</a></li>
<li><a href="http://tech.groups.yahoo.com/group/ydn-javascript/">YUI Discussion Forum</a></li>
<li><a href="http://developer.yahoo.com/yui/docs/">API Documentation</a></li>
<li><a href="http://developer.yahoo.com/yui/examples/">YUI Examples Gallery</a></li>
<li><a href="http://developer.yahoo.com/yui/poweredby/">Sites Powered by YUI</a></li>
<li><a href="http://gallery.yahoo.com/yui">Yahoo! Gallery &#8211; YUI</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.klauskomenda.com/archives/2007/10/13/agent-yui-introduction/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

