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:


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

  var icon = document.getElementById("icon");
  function changeIcon() {
  if (icon.src="play.svg")


Welcome to the forums @dmartins2005

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.

= 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.


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


“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.)


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