Busted Mug

A blog that documents solutions to the most frustrating problems that occur during development in technologies such as Java, XML, AJAX, SQL, CSS and others that make me want to throw my coffee mug against the cube wall.

Monday, March 05, 2007

Dynamic Assignment of Event Handlers - A generic rollover event

Rollovers are so often done badly and you have to write code for every image. No more. It is much better to use some code as follows to make a generic function and then apply it generically as I have using the class attribute.

function start(){
var els = document.getElementsByTagName('img');
if(els[i].className == "rollover"){
els[i].onmouseout swap;

function swap(){
var src = this.src;
pos = this.src.indexOf("_over");
tmp = new Image();
(pos == -1){    
src.substring(0,src.length-4) + "_over" + src.substring(src.length-4);
.src tmp.src;
this.src src.substring(0,pos) + src.substring(pos+5);
<body onload="start();">
<img src="x.gif" id="hi" class="rollover" />

Doh! Be sure to read the update to this post, too. I forgot to preload those images :x