Agent YUI: Mission 1 – Attaching Events (the easy way)

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 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.

The Plan

So we have 2 different scenarios:

  1. JavaScript is available: randomly display an image from the pool
  2. JavaScript is not available: lead user to a page with all the images

The Implementation

The HTML markup we are starting with looks like this (and you can also check it in the initial file):

<a href="all.html" id="switch">Show me more, James</a>
<img src="daniel_craig.jpg" alt="James Bond Picture" id="picture" />

We will only make use of the YUI Core components, so all we need to include is the yahoo-dom-event.js file from the recent YUI build.

<script type="text/javascript" 
src="http://yui.yahooapis.com/2.3.1/build/yahoo-dom-event/yahoo-dom-event.js"></script> 

After that, we need to create our main object, which we will use to wrap around our functions:

YAHOO.namespace("AgentYUI");

As this is the our first mission, we will define our module like this:

YAHOO.AgentYUI.Mission1 = function () {}();

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:

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)];
};

What happens here?

Blofeld: The satellite is now over… Kansas. Well, if we blow up Kansas the world may not hear about it for years.

from Diamonds Are Forever

YAHOO.util.Dom.get(“picture”) returns a reference to the HTML object on the page with the id “picture”. 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).

Now it is time to bring the Event Component 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 YAHOO.util.Event, to attach the behavior, like so:

var init = function () {
    // attach event to anchor
    YAHOO.util.Event.addListener("switch", "click", switchImage);
};

What happens here?

YAHOO.util.Event.addListener gets the element with the ID “switch” and attaches an “onclick” event. If that event is fired, switchImage gets executed.

With a little tidying up and proper use of the revealing module pattern, we get a result 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 preventDefault. We will add that to our switchImage function like so:

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)];
};

What happens is: e is the event object that gets passed into the function automatically by the YUI. With that object at hand, we can use YAHOO.util.Event.preventDefault to prevent the browser from redirecting to the next page. So we did it. Take a look at the final result.

Further Reading