April 21, 2007

April 07 Meeting - Unobtrusive Image Rollover

After finishing the main topics from our book for this season, I'd thought I'd update an example we covered last season using some of the DOM techniques we have learned so far. Back in the January 06 meeting I showed you how to create image rollovers using the Image object and the onMouseOut and onMouseOver event handlers. The code worked fine, but had a small problem.

What do you see wrong with this code?

<a href="newpage.html"
onMouseOver="MouseOn('mouse1');"
onMouseOut="MouseOff('mouse1');">
<img name="mouse1" src="mouse_out.gif" border="0" />
</a>

If you attended the December 06 meeting you would know that putting inline event handlers prevents your code from being "unobtrusive". Meaning there is no separation between the structure (HTML) and the behavior (JS). Any needed changes to your image swapping becomes very time consuming because each event handler needs to be modified within your .html page.

A better solution would be:

<a href="newpage.html">
<img src="mouse1.gif" id ="mouse1" border="0" />
</a>

You would use a "hook" like an id or class value to identify all elements that would require the image swapping without using inline event handlers. All the code would be stored in an external .js file with the references to DOM elements being easily updateable without ever having to touch your HTML.
Nice and neat. :)

Check out the downloads page to download and see the complete code.

Here are some great videos narrated by Dori Smith that review this technique as well as show additional techniques such as making links more accessible and creating disjointed rollovers:

Unobtrusive Rollovers
Accessible Rollovers
Disjointed Rollovers