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.
<head>
<script>
function start(){
var els = document.getElementsByTagName('img');
for (i=0; i<els.length; i++){
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
<< Home