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?

3
  • 1
    add double quotes around Shopping3.png Commented Mar 23, 2013 at 1:51
  • change to onclick='changeImage("Shopping3.png"); Commented Mar 23, 2013 at 1:52
  • Put quotes around the file name when you call your function... Commented Mar 23, 2013 at 1:52

2 Answers 2

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");'/>
Sign up to request clarification or add additional context in comments.

Comments

2

You need to pass Shopping3.png as a string.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.