0

not sure if this is possible keeping the code simple, but im trying to make it so that i have an image, when you clicked it, it goes to a new image. then when you click that image, it goes back to the original image. my code is:

function save_data()
{
if ( document.images.save.src == "saved.png") document.images.save.src="save.png";
if (document.images.save.src == "save.png") document.images.save.src="saved.png";
}


<img id="save"  onclick="save_data()" src="save.png">
Lan
  • 1,874
  • 2
  • 20
  • 37

2 Answers2

3

It can be simplified.

Using

<img id="save"  onclick="save_data(this)" src="save.png">`

You can do

function save_data(img)
{
  img.src = /saved/i.test(img.src) ? 'save.png' : 'saved.png';
}

If this doesn't work, it may have to do with the fact that saved.png is not in the path the html is in. So try it with a full URL:

function save_data(img)
{
  var imgpath = 'http://yoursite.com/imgpath/';
  img.src = imgpath + (/saved/i.test(img.src) ? 'save.png' : 'saved.png');
}

A note: it may be better to assign the click handler unobtrusively (see also this SO question)

Community
  • 1
  • 1
KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

if ( document.images.save.src == "saved.png") - this won't work, because .src returns the full path to the image, not just the filename. For example, http://site.com/path/images/saved.png.

Try matching substrings instead.

function save_data()
{
if ( document.images.save.src.indexOf("saved.png") != -1) document.images.save.src="save.png";
if (document.images.save.src.indexOf("save.png") != -1) document.images.save.src="saved.png";
}
Nadh
  • 6,987
  • 2
  • 21
  • 21