the problem is I want to change the src of img tag by using the button which executes if, else function. but I think my code is unprofessional and there is a better way to do the same job.
JavaScript
x
11
11
1
let smile = true
2
let test = () => {
3
if (smile == true) {
4
document.getElementById("image").src = "https://images.freeimages.com/images/large-previews/adb/fruit-in-a-bowl-1637721.jpg";
5
smile = false
6
}
7
else {
8
document.getElementById("image").src = "https://images.freeimages.com/images/large-previews/a33/fresh-red-ripe-strawberries-1641723.jpg";
9
smile = true
10
}
11
}
JavaScript
1
2
1
<img id="image" src="https://images.freeimages.com/images/large-previews/a33/fresh-red-ripe-strawberries-1641723.jpg" width="160" height="120">
2
<button type="button" onclick="test()">over here </button>
Advertisement
Answer
Here is another solution, wich is just 5 lines of JS. It uses if-else oneliners, to wich a detailed guide can be found here.
I also used the HTML data-attribute instead of a variable:
data-smile="false"
I removed the id of the Element because you can just select it via the data-attribute.
JavaScript
1
5
1
let img = document.querySelector('[data-smile]');
2
img.onclick = () => {
3
img.dataset.smile = img.dataset.smile == "true" ? "false" : "true";
4
img.src = img.dataset.smile == "true" ? "https://i.imgur.com/jgyJ7Oj.png" : "https://i.imgur.com/PqpOLwp.png";
5
}
JavaScript
1
3
1
<div>
2
<img src="https://i.imgur.com/PqpOLwp.png" data-smile="false">
3
</div>
Hope that helps 🙂