Skip to content
Advertisement

Changing images onclick

I want the image to change when someone clicks on it, but this isn’t working.

JavaScript

Can someone explain me the reason?

Advertisement

Answer

Your code is not working because you use retrieved the value of src and placed it in a variable called replace like so:

JavaScript

After that you changed the content of the variable like so:

JavaScript

All a variable does is hold a value. You just changed the value/content that the variable holds, which results in nothing happening.

What you should do is have the variable hold the element itself, like so:

JavaScript

Then have javascript change the src property/attribute of the element it holds, like so:

JavaScript

I hope this clears out your doubts 🙂

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement