Martin Martin - 7 months ago 20
Javascript Question

Change image using event listener

I have two images:

images/pic1.png
and
images/pic2.png
. And I want to make something like this:
When I click on image(pic1) for the first time it changes its
src
to
images/pic2.png
and then 2nd image is displayed. Next, I click again (2nd time), and my first image is displayed again. And if I click for the third time my 2nd img is displayed again. And again and again and again.

Also, I'd like to make it with loop
if(...) ... else{...}
.

Here's my code:

HTML

<img src="images/pic1.png" id="myImage"/>


JS

var img = document.getElementById("myImage");
img.addEventListener("click", function(){
if(img.src != "images/pic2.png"){
img.src = "images/pic2.png";}
else{
img.src = "images/pic1.png";}});


I do not know what else to do...

Answer

here is a working example that shows your code works fine. Unless you are having a problem because of ABSOLUTE VS RELATIVE URLS.

var img = document.getElementById("myImage");
img.addEventListener("click", function(){
  if(img.src != "http://placehold.it/350x150/ff0000"){
    img.src = "http://placehold.it/350x150/ff0000";}
  else{
    img.src = "http://placehold.it/350x150";}});
<img src="http://placehold.it/350x150" id="myImage"/>

Comments