Cant get image to change when clicked

im trying to get a image to change everytime its clicked, visa-versa. now it will change once, but thats it. Its driving me mad, any ideas where im going wrong?

thanks

<script type="text/javascript">
  function toggle_visibility(id) {
	 var f = document.getElementById('helptext2');
	 if(f.src == 'assets/expand_help.png')
		f.src = 'assets/expand_help.png';
	  else
		f.src = 'assets/expand_help_down.png';
  }</script>
         <a href="#" onClick="toggle_visibility('helptext')">
            <img src="assets/expand_help.png"  id="helptext2" /> change image  </a>

Take a closer look at the logic of your if/else statements.

Aside from the logic problem there’s the “src contains the full path” issue. Also if you’re going to pass an ID you may as well use it, and why not make the function reusable?:

<script type="text/javascript">

function toggle_visibility(id, a, b) 
{
 var f = document.getElementById( id );

 f.src = ( f.src.indexOf( a ) > -1 ) ? b : a;
}

</script>

<a href="#" onClick="toggle_visibility('helptext2', 'assets/expand_help.png', 'assets/expand_help_down.png')">
            <img src="assets/expand_help.png"  id="helptext2" /> change image  </a>




another option

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
 
var picPaths = ['pic1.jpg','pic2.jpg'];
var currPic = 0;
 
function toggleImage(elem) {
    currPic = (currPic == 0)? 1 : 0;
    elem.src = picPaths[currPic];
}
 
</script>
</head>
<body>
 
<div>
        <img src="pic1.jpg" alt="" onclick="toggleImage(this)" />
</div>
 
</body>
</html>

That creates two unnecessary global objects, and the hard coded array name restricts the function to one use. Not always an option.

no problem :slight_smile:

I said it’s just another option, not the way it must or should be done by anyone else.

in the absence of any more specific details from the op regarding their requirements, it’s the way I will always choose to do it.

thank you both for your help, worked great.
but then i thought i might try optimise my code i have elsewhere.
Basicly you click the image, it changes and also hides/unhides a div id…
I tryed to reference the code you gave me, and tryed a few changes but i can get it to show (from its default hidden). but i cant get it to hide again etc.

<script type=“text/javascript”>

function toggle_visibility(id, a, b) 
{
 var f = document.getElementById( id+'img' );
 var e = document.getElementById( id );
 f.src = ( f.src.indexOf( a ) > -1 ) ? b : a;
 e.style.display =  ( e.style.display > -1 ) ? 'none' : 'block';
}

</script>
 e.style.display =  ( e.style.display.indexOf( 'block' ) > -1 ) ? 'none' : 'block';

ok, so i played a little more and found this works, :slight_smile: