'Onclick function in js not working properly
onclick function to change an image once clicked but its giving me an error in Js saying unexpected else please I need an assistance Im a newbie in programming
function changeImage(){
let a=document.getElementById("changeimg").src
if (a==="img/save.png") {
return a = "img/saveblack.png"
}
}
else{
return a= "img/save.png"
}
</div>
<div class="wrapper_center">
<img src="img/profilepix.jpg">
</div>
<div class="wrapper_bottom">
<div class="reaction_wrapper">
<a href=""><img src="img/heart.png"></a>
<a href=""><img src="img/messagereaction.png"></a>
<a href=""><img src="img/message.png"></a>
<img src="img/save.png" id="changeimg" onclick="changeImage()">
</div>
Solution 1:[1]
Try this ( I suggest you use a good text editor lik vscode, webstorm, itellij or atom, all the syntax errors you have will be highlighted)
function changeImage(){
let element = document.getElementById("changeimg")
element.src = element.src ==="img/save.png" ? "img/saveblack.png" : "img/save.png";
}
<div class="wrapper_center">
<img src="img/profilepix.jpg">
</div>
<div class="wrapper_bottom">
<div class="reaction_wrapper">
<a href="">
<img src="img/heart.png">
</a>
<a href=""><img src="img/messagereaction.png"></a>
<a href=""><img src="img/message.png"></a>
<img src="img/save.png" id="changeimg" onclick="changeImage()"> </div>
</div>
Solution 2:[2]
The curly bracket on line 7 should be moved to below the else statement. The way it currently is, you're closing the function, and then have an else clause not tied with an if.
Also, setting a to element.src will just copy the value of element.src to the variable a, so if you change a at all it won't change element.src at all. You can fix this by saving a as element so that you can modify the properties, since objects (not primitives) are copied by reference and not value.
function changeImage() {
let a = document.getElementById("changeimg");
if (a.src === "img/save.png") {
return a.src "img/saveblack.png"
} else {
return a.src = "img/save.png"
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Meddah Abdallah |
| Solution 2 |
