JavaScript syntax question
I have a function that switches a larger image for a smaller one on mouseovers, the code is here:
function SwapOutStaff(number)
{
document.staff.src = swapImage[number].src;
return true;
}
<a href="somefile.html" onmouseover="SwapOutStaff(6)" ><img class=""src="staff.jpg" width="140" height="100" alt="" border="0" name="staff" /></a>
What I want to be able to do is to change the name of the image that is swapped dynamically, because I have a lot of images that need to be swapped, and it is dumb to write a seperate function for each one. I want to be able to do something like this:
function SwapOut(number,name)
{
document.NAMESUPPLIEDHERE.src = swapImage[number].src;
return true;
}
<a href="somefile.html" onmouseover="SwapOut(6,'staff')" ><img class=""src="staff.jpg" width="140" height="100" alt="" border="0" name="staff" /></a>
I have tried a number of strategies but none have worked. Is it even possible to do this in JavaScript. Any information would be helpful.
function SwapOutStaff(number)
{
document.staff.src = swapImage[number].src;
return true;
}
<a href="somefile.html" onmouseover="SwapOutStaff(6)" ><img class=""src="staff.jpg" width="140" height="100" alt="" border="0" name="staff" /></a>
What I want to be able to do is to change the name of the image that is swapped dynamically, because I have a lot of images that need to be swapped, and it is dumb to write a seperate function for each one. I want to be able to do something like this:
function SwapOut(number,name)
{
document.NAMESUPPLIEDHERE.src = swapImage[number].src;
return true;
}
<a href="somefile.html" onmouseover="SwapOut(6,'staff')" ><img class=""src="staff.jpg" width="140" height="100" alt="" border="0" name="staff" /></a>
I have tried a number of strategies but none have worked. Is it even possible to do this in JavaScript. Any information would be helpful.
Comments
Try something like this:
function SwapOut(number,name)
{
"document."+name+".src" = swapImage[number].src;
return true;
}
If that doesn't work, you could try something more like this... but I have my doubts about this syntax:
function SwapOut(number,name)
{
docName="document."+name;
docName.src = swapImage[number].src;
return true;
}
JS is funny like this... since the variables aren't typed as they are in some other languages, it can be both easier and harder to do something like this.
BTW: [CODE] tags are your friend