1

I 've got an image in my application. I try to change this image to another by onclick event, but I don't know why it doesn't work. Here is my code:

<body>
<div> 
  <img onclick="click()" src="http://chittagongit.com//images/smile-icon/smile-icon-6.jpg" id="smile">
</div>
<script>
  function click () {
    document.getElementByID("smile").src = "http://chittagongit.com//images/smile-icon/smile-icon-5.jpg"
  }
</script>

The same code at codepen: https://codepen.io/szczypkamaciek/project/editor/DBrPbw

Thanks for help!!!

mackosz
  • 139
  • 1
  • 8

3 Answers3

1

Make sure to check the console when things are working the way you expect. You misspelled "getElementByID" it should be "getElementById" (lower-case "d").

Also it's generally better practice to use addEventListener:

<script>
  var smile = document.getElementById("smile");
  smile.addEventListener('click', function () {
    smile.src = "http://chittagongit.com//images/smile-icon/smile-icon-5.jpg"
  });
</script>
Ryan Badour
  • 584
  • 3
  • 14
0

Mistake document.getElementById Id not with capital ID

function click() {
    document.getElementById("smile").src = "http://chittagongit.com//images/smile-icon/smile-icon-5.jpg"
}
0

There are two problems in this code:

  1. Misspeled getElementById (insted of getElementByID)
  2. Your code can't work in this form becuase you are using click() as your function name. Using click this way will fire click event, not your function - you can read more here: click() in JS

Anyway in general it's better practise to use listeners instead of direct node declaration.

Griva
  • 1,618
  • 20
  • 37