Keeping it simple with image rollovers, part 2

So in the last installment of simple rollovers I mentioned that one of the issues with the various rollover demos in the Internet is that they don't scale very well. Let me explain.

A Google search uncovered a few examples of what I am writing about. Most tutorials are completely focused on getting you to type in a couple of lines of JavaScript (or CSS). They never take the next step and show you how to apply such a technique en masse.

So let's take a look at the CSS for a rollover using :hover:

#rollover {
background-image: url('images/one.png');

#rollover:hover {
background-image: url('images/two.png');


<div id="rollover-1"></div>

Now assume that we have five rollovers on the same page:

<div id="rollover-1"></div>
<div id="rollover-2"></div>
<div id="rollover-3"></div>
<div id="rollover-4"></div>
<div id="rollover-5"></div>

If we were to continue to use the same technique, we would need 10 CSS declarations-- two for each DIV. For 100 DIVs we'd need 200. Too much typing! I'm lazy and can't be bothered to engage in such endeavors. Which leads us to JavaScript.

<script type="text/javascript">

function showRolloverImage(rollover) {
var imageUrl = + "-rollover.png"; = "url(" + imageUrl + ")";

function hideRolloverImage(rollover) {
var imageUrl = + "-norollover.png"; = "url(" + imageUrl + ")";


The first function, showRolloverImage(), will swap out the div's current CSS background-image for a different one. Then hideRolloverImage() can be used to restore the original one.

Back in the HTML, we can call each of these JavaScript functions by using the onMouseOver and onMouseOut attributes:

<div id="one" onmouseover="showRolloverImage(this)" onmouseout="hideRolloverImage(this)"></div>
<div id="two" onmouseover="showRolloverImage(this)" onmouseout="hideRolloverImage(this)"></div>
<div id="three" onmouseover="showRolloverImage(this)" onmouseout="hideRolloverImage(this)"></div>

This will cause the images to be swapped when the mouse moves over each div. All it requires is that you name the images appropriately-- the div's id should be the base name of the image, and the JavaScript will append '-rollover.png' or '-norollover.png' to it as necessary.

The only thing missing then is how to load an image into the div initially when the page loads. I'll cover that and bring it all together in part 3.


Popular posts from this blog

Monitoring with statsd and CloudWatch

Xen, "hwcap 0 nosegneg", and -mno-tls-direct-seg-refs

A Grand Adventure: compiling transmission on my home router