Can someone explain why this code works and this doesn't?

This code works.

 <script>
  window.onload = init;

	function init() {
		var images = document.getElementsByTagName("img");
		for (var i = 0; i < images.length; i++) {
			images[i].onclick = showAnswer;
		}
	};

	function showAnswer(e) {
		var image = e.target;
		var name = image.id;
		name = name + ".jpg";
		image.src = name;
	}
  
  </script>

and this doesn’t:

 window.onload = init;

   function init() {

       var images = document.getElementsByTagName("img");
       for (var i = 0; i < images.length; i++) {
           images[i].onlick = showAnswer;

       }
      
   };

   function showAnswer(eventObj) {
      var image = eventObj.target;
      var name = image.id;
      name = name + ".jpg";
      image.src = name;
   }

Can someone please explain why eventObj doesn’t get passed but e does??

In the second code snippet, you have a typo.

// `onlick` - no such thing
images[i].onlick = showAnswer;

Make it onclick and it will work just like your first snippet.

1 Like

Thanks a lot husseyexplores :slight_smile: