Change image src with javascript

Asked

Viewed 184 times

1

I’m trying to make the image change every time I click the button, so that when I click on image1 it becomes image2 and when I click not image2 it becomes image1

<script>
function changeImage(){
  var image = document.getElementById("image");
  if(image.src = "image1.png"){
      image.src = "image2.png";
  }
  else if(image.src = "image2.png"){
      image.src = "image1.png";
  }
}
<img id="image" src="image1.png" width="490" height="364">

<button onclick="changeImage()">Mudar image</button>

only that it can only become image2, after that it is not back to image1

2 answers

3


It seems that it remains to study a little more, in the comparison has to be at least 2 equal for loose test (only tests the value) or 3 equal when you want to test type and value (which is recommended), example:

function changeImage(){
  var image = document.getElementById("image");
  if(image.src === "image1.png"){
      image.src = "image2.png";
  }
  else if(image.src === "image2.png"){
      image.src = "image1.png";
  }
}

or be correct in comparison is:

  • image.src === "image1.png"
  • image.src === "image2.png"

in the assignment of values is correct only 1 equal.

Another example:

function changeImage(){
  var image = document.getElementById("image");
  if(image.src === "https://via.placeholder.com/150/d32776"){
      image.src = "https://via.placeholder.com/150/efefef";
  }
  else if(image.src === "https://via.placeholder.com/150/efefef"){
      image.src = "https://via.placeholder.com/150/d32776";
  }
}
<div>
  <img id="image" src="https://via.placeholder.com/150/d32776" />
</div>
<button onClick="changeImage()">Mudar</button>

0

Rodrigo, I believe that the flaw in your code is that you are not comparing when you 1 = because that way you are assigning value to variable and not comparing. In javascript you compare with == or also with ===

I’ve set up an audio package that I believe can assist but next questions:.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operadores_de_compara%C3%A7%C3%A3o#:~:text=%20JavaScript%20has%20compares%C3%A7%C3%B5es%20strict, even%20type 20before%20compare%C3%A7%C3%A3o

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.