Search code examples
jqueryhtmlfireworks

What's wrong with my HTML/jQuery toggle script?


I have this function in a script in the header (generated by Fireworks, it works):

function MM_swapImage() { //v3.0
var i,j=0,x,a=MM_swapImage.arguments; 
document.MM_sr=new Array;
   for(i=0;i<(a.length-2);i+=3)  
      if ((x=MM_findObj(a[i]))!=null){
         document.MM_sr[j++]=x; 
         if(!x.oSrc) 
            x.oSrc=x.src; 
            x.src=a[i+2];
      }
}

Then I have a table with a bunch of td and trs, including this one:

   <td rowspan="2"><a href="javascript:;" onclick="MM_swapImage('slice1_s1','','images/slice1_s2.jpg',1);"><img name="slice1_s1" src="images/slice1_s1.jpg" width="146" height="87" border="0" id="slice1_s1" alt="" /></a></td>

Then, after the table ends, I put this script:

<script>
$("img").toggle(function(){
   $(this).MM_swapImage('slice1_s1', '', 'slice1_s2.jpg', 1); 
}, function(){
   $(this).MM_swapImage('slice1_s1', '', 'slice1_s1.jpg', 1); 
});
</script>

The tables and all are just the way Adobe Fireworks slices stuff up for the web, so that's all generated as well.

Here's what I want to happen: When the picture is clicked, I want it to change color (which is a second image I have ready, slice1_s2.jpg). When it is clicked again, I want it to go back to original. When I test this, nothing happens. Any suggestions?


Solution

  • Felix Kling's comment, I believe, is correct. I can't say for sure since I can't see all the code that you're using - but it makes sense. I took your code and mocked up a local version. I got an error where $(this).MM_swapImage was called, saying the object wasn't defined. Once I removed $(this)., I got a different error in MM_swapImage (because I don't have all the code), but this indicates the root of your problem.

    But a question I have is why not just use jQuery's toggle method to swap out the image? You could just do this:

    $("img").toggle(function(){
        $(this).attr("src", "slice1_s2.jpg");
    }, function(){
        $(this).attr("src", "slice1_s1.jpg");
    });
    

    Not sure if you have to use MM_swapImage or not.

    Felix Kling should get the correct answer. I just wanted to throw in using toggle to swap your image.

    Hope this helps!