0

So im new with javascript and found this one to solve my problem:

Change image source with javascript

But the example does not work for me.

<script type="text/javascript">
  function changeImage(a) {
    document.getElementById("img1").src=a;
  }
</script>

And

<table align=left width="896px" class="tableCategories">
  <tr class="trCategories">
    <td class="tdCategories">
      <img id="img1" src="./icon/menu/Essen3.png" onclick='changeImage(Shopping3.png);'/>
    </td>
  </tr>
</table>

So if i click on the image it does not change itself. The path to the images are correct. What am i doing wrong?

Community
  • 1
  • 1
Kingalione
  • 4,237
  • 6
  • 49
  • 84

2 Answers2

5

Change

<img id="img1" src="./icon/menu/Essen3.png" onclick='changeImage(Shopping3.png);'/>

To

<img id="img1" src="./icon/menu/Essen3.png" onclick='changeImage("./icon/menu/Shopping3.png");'/>

A better javascript function would be re-usable. Try this:

function changeImage(obj,img) {
  obj.src = img;
}

and the following HTML code:

<img id="img1" src="./icon/menu/Essen3.png" onclick='changeImage(this,"./icon/menu/Shopping3.png");'/>
Chris White
  • 709
  • 1
  • 5
  • 8
2

You need to pass Shopping3.png as a string.

<img id="img1" src="./icon/menu/Essen3.png" onclick="changeImage('Shopping3.png');"/>
ryan
  • 6,541
  • 5
  • 43
  • 68