Change img source

hello guys, im needing some help here. i started to learn java this week, and i havi this function to change the image source, but, it just changes once, and i want it to change everytime i click on the button.

some ideias of what can i do?

this is the code:

<html>
<body>

<div onclick= "changeIcon()">
   <img id="icon" src=play.svg height="250px"></img>
</div>

<script>
  var icon = document.getElementById("icon");
  function changeIcon() {
  if (icon.src="play.svg")
      icon.src="pause.svg";
            
  else
      icon.src="play.svg";
  }
</script>

</body>
</html>

Welcome to the forums @dmartins2005

[off-topic]
When you post code in the forum, you need to format it. To do so you can either select all the code and click the </> button, or type 3 backticks ``` on a separate line both before and after the block of code.

I have done it for you this time.
[/off-topic]

= is an assignment so will always be true. That’s why you always get the same result.

== is the equality operator (or ‘===’).

Your conditional statement should use the equality operator(==) and then when you assign a value use the assignment operator (=).

It would also be better to remove the onclick from the html and do it from the js file instead where it belongs…

Also tidy your brackets up on the if/else code.

e.g.

No! You started to learn JavaScript :slight_smile: Java is a completely different language :wink:

3 Likes

“Java is to Javascript as Pen is to Penguin.”

Though I will say, if this is your first week with Javascript, and you came up with this code on your own, you’ve got a very strong foundation.

(EDIT: I cant read. Go me.)

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.