JavaScript syntax question

Posted:
in Genius Bar edited January 2014
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.

Comments

  • Reply 1 of 3
    baumanbauman Posts: 1,248member
    Well, I'm not a l33t JS expert, but here's my go at it:



    Try something like this:



    Code:




    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:

    Code:




    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
  • Reply 2 of 3
    rick1138rick1138 Posts: 938member
    Thanks, I'll try that-hopefully it will work.
  • Reply 3 of 3
    rick1138rick1138 Posts: 938member
    Looks like that doesn't work either. Oh well. Thanks though.
Sign In or Register to comment.