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.

<html>
<head>
<script>
    
function start(){
        
var els = document.getElementsByTagName('img');
        for 
(i=0i<els.lengthi++){
            
if(els[i].className == "rollover"){
                els[i].onmouseover 
swap;
                
els[i].onmouseout swap;
            
}
        }
    }

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

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