Forum Moderators: open
I'm coding the images like so:
<img src="images/somefile_out.gif" class="rollover" /> And I call this function from an external file right before the closing </body> tag:
function addRollovers() {
var rollers;
if(document.getElementById)
rollers = document.getElementsByTagName('img');
else if(document.all)
rollers = document.all.tags('img');
else return
for (var i=0; i<rollers.length; i++) {
var roller = rollers[i];
if (roller.className == 'rollover'){
var rolloverSRC = roller.src.replace('_out',"_over");
roller.onmouseover = function(){ this.src=rolloverSRC; }
roller.onmouseout = function(){ this.src=roller.src; }
}
}
} Problem: The script gives every matching image a onmouseover to change into the SRC of the last img in the array and an onmouseout of the next to last img in the array. So, all the rollover images do the same thing, as if they are using the last written version of the function instead of the version written on their iteration of the loop.
I've put the function declaration outside the loop for a little pedantic efficiency.
(Haven't tested this myself as yet).
function addRollovers()
{
var rollers;
if(document.getElementById)
rollers = document.getElementsByTagName('img');
else if(document.all)
rollers = document.all.tags('img');
else returnfor(var k=0,roller; roller=rollers[k]; )
{
if (roller.className!= 'rollover') continue;
roller.onmouseover = roller.onmouseout = roll;
}function roll()
{
if( /_out/.test(this.src) )
this.src = this.src.replace('_out','_over');
else
this.src = this.src.replace('_over','_out');
}
}
The assignment can be placed in the HEAD, or linked script.
document.onmouseover =
document.onmouseout = function(e)
{
// Get source element of bubbled event (X-browser)
e = e ¦¦ event;
var elm = e.srcElement ¦¦ e.target;
// Allow possibility of multiple className
if(! /\brollover\b/.test(elm.className) ) return;
elm.src = /_out/.test(elm.src)
? elm.src.replace('_out','_over')
: elm.src = this.src.replace('_over','_out');
}
(This approach does work- but there may be a silly mistake in the above)
I think it's because this part:
elm.src = /_out/.test(elm.src) Always tests true because it's testing the actual code and not the modified src? Or is there something else going on here?
Also, thanks very much! I didn't even know about .test and was concerned about multiple class names fouling my original script. :D