views:

66

answers:

1

I have a FireWorks-generated HTML page and I added some jQuery to it for desired effects...it's for a pain study, so when you click a part of the spine, it lights up in red. I added jQuery's toggle for sort of an "unclick" option, but it's not working as expected. (Similar to a previous question I asked, but different enough IMO).

When I click the first time, it does light up red as expected. When I click the second time, it goes back to unclicked, then instantly goes back to red, as though both toggle events were fired, so fast that it's like the second click didn't even register (I know it does fire though; I rigged up a pseudo-debug scheme with alerts to make sure the second function was run). Any ideas on what I did wrong?

Here is some relevant code:

jQuery script:

<script type="text/javascript">
$(document).ready(function(){
   $("img.toggle1").click(function(){
      $("img.toggle1").toggle(function(){ 
        alert('first click');
          $(this).attr('src', 'images/cervical_s7.jpg');
      }, function(){ 
          alert('second click');
          $(this).attr('src', 'images/cervical_s1.jpg');
      });
   });
});
</script>

Noteworthy snippets of generated HTML (the table containing the image created by the slice, and the image map created by the slice. I removed the onclick behavior in place of the toggle, and the onMouseOver is for an effect on a different image):

   <td rowspan="2"><img name="cervical_s1" class="toggle1" src="images/cervical_s1.jpg"
    width="185" height="121" border="0" id="cervical_s1" usemap="#m_cervical_s1"
    alt="" /></td>

<map name="m_cervical_s1" id="m_cervical_s1">
<area shape="poly" class="toggleCerv" coords="159,0,154,29,151,57,154,95,165,
       113,185,121,0,121,14,111,23,93,24,43,19,0,48,7,96,7,140,3,159,0,159,0" 
       href="javascript:;  alt="" onmouseover="MM_swapImage
       ('sign_s1','','images/sign_s2.jpg',1);"  /> </map>

tl;dr - jQuery toggle seems to fire twice after the first click so it's stuck in toggle position #2.

EDIT: When I click again, I get 3 alternating alerts, then 4 alternating alerts, etc. Thanks for the helpful comment. Hopefully this makes it easier to figure out?

Thanks!

+1  A: 

Look at http://api.jquery.com/toggle/

You don't need to register click().

So instead of:

$("img.toggle1").click(function(){
      $("img.toggle1").toggle(...);
   });

Put

$("img.toggle1").toggle(...);
Nicolas Viennot
then do the toggling yourself: `$("img.toggle1").click(function(){ if $(this).attr("src").match(/enabled/) { ... } else { ...} });
Nicolas Viennot
Herp derp I'm an idiot. You got it. (I forgot to remove the extra braces afterwards)
rownage
Thanks for your help...I really appreciate it!
rownage