I want the image to change when someone clicks on it, but this isn’t working.
JavaScript
x
7
1
<image id="s" src="s.jpg" onclick="reaction()" ></image>
2
function reaction()
3
{
4
var replace=document.getElementById("s").src;
5
replace="20141018_222702.jpg";
6
}
7
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
1
2
1
var replace=document.getElementById("s").src;
2
After that you changed the content of the variable
like so:
JavaScript
1
2
1
replace="20141018_222702.jpg";
2
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
1
2
1
var replace=document.getElementById("s");
2
Then have javascript change the src
property/attribute of the element it holds, like so:
JavaScript
1
2
1
replace.src="20141018_222702.jpg";
2
I hope this clears out your doubts 🙂