2

This seems like it should work but doesn't. I'm not sure where the problem is - either I'm doing it wrong, or it's possible I have a syntax error. I just doesn't do anything. I'm trying to get the current picture to change when the button is clicked. I'm a beginner at Javascript, so please be gentle ;) Thank you!

<html>
<script>
function pictureChange()
{
document.getElementById(theImage).src="http://31.media.tumblr.com/fca646cd8fe87906e605ad7e8d039903/tumblr_mmoz4fWT6U1soh1p8o1_500.png");
}
</script>
<body>
<img id="theImage" src="http://31.media.tumblr.com/18b5f8f0a00ad01e50f7ae2f513be52d/tumblr_msqcl4iwM01soh1p8o1_500.png">
<p><input type="button" id="theButton" value="click me!" onclick="pictureChange()"></p>
</body>
</html>
user2884447
  • 21
  • 1
  • 1
  • 2
  • 6
    This is something that you can debug yourself. Look in the [JavaScript error console](http://www.netmagazine.com/tutorials/javascript-debugging-beginners) and check what the error message says. – JJJ Oct 26 '13 at 17:03

4 Answers4

5

You missed the quotes in .getElementById('theImage')

 function pictureChange()
    {
    document.getElementById('theImage').src="http://31.media.tumblr.com/fca646cd8fe87906e605ad7e8d039903/tumblr_mmoz4fWT6U1soh1p8o1_500.png";
    }
Roar
  • 2,117
  • 4
  • 24
  • 39
3

Add " to getElementById argument and remove ) at the end of the line:

<script>
    function pictureChange()
    {
          document.getElementById("theImage").src="http://31.media.tumblr.com/fca646cd8fe87906e605ad7e8d039903/tumblr_mmoz4fWT6U1soh1p8o1_500.png";
    }
</script>

http://jsfiddle.net/cDd8J/ - here. It works.

theImage is just id of the element, not variable, so you have to put it in quotes.

Crazy Yoghurt
  • 2,365
  • 2
  • 26
  • 37
-1

There are lot of ways you could try.Calling the function using inline attributes or calling it using the id in your script.Here's one ,

theButton.onclick = function pictureChange()
{
   document.getElementById("theImage").src="http://31.media.tumblr.com/fca646cd8fe87906e605ad7e8d039903/tumblr_mmoz4fWT6U1soh1p8o1_500.png";
}

Demo

Md Ashaduzzaman
  • 4,032
  • 2
  • 18
  • 34
-1

You can use inline HTML: <img src="img1.jpg" onclick="this.src='img2.jpg'"> works best.