Unobtrusive image rollover

Remember the old days where you put your javascript code on the image to do the rollover?

Something like:

<img src="mypicture.jpg" onmouseover="rolloverme()" onmouseout="rollmeout()" name="myimage">

This works fine, but when you rename the rolloverme() function into a different function (in your javascript file) for example rollme1() and you move your mouse over the image, you will get a javascript error.

And when you use Dreamweaver to rollover the functions rolloverme() and rollmeout() gets more complicated (extra params and stuff).

So I started thinking, this could be easier.

DOM scripting

So to do things different, I'm gonna enter the world of DOM-scripting. First I've downloaded the behaviour script made by Ben Nolan. With the script you can attach javascript code on your CSS selectors.

The images

So I have 2 images:

How it works

First I started with the normal image:

<img src="normal.jpg" border="0" alt="Rollover me">

Next I added a class: img_rollover

<img src="normal.jpg" border="0" alt="Rollover me" class='img_rollover'>

Now I need to define a ID for the image. And here's when the "magic" happens. The ID stores the image-filename to be rollovered (and back again). The ID starts with the string: "rollover__" and then the filename comes (without the file extention). So in my example I want to show rollover.jpg so my ID would be

rollover_rollover

And my img would be:

<img src="normal.jpg" border="0" alt="Rollover me" class='img_rollover' id="rollover_rollover">

Next with the help of the behaviour script I put the onmouseover and onmouseout events on all the images who uses the class img_rollover.

My files

So these are the files I've used:

The result

Rollover me

Conclusion

So it works, but I think it needs more debugging but it works for me right now ;-). Hope you can use it.

Fransjo Leihitu
http://www.leihitu.nl free web site hit counter