Issue
hello is there any other way to get the same result as we see down goal is : changing the "src" attribute with one button and function
<img id="image" src="path of picture1" width="160" height="120">
<button type="button" onclick="test()">over here </button>
<script>
let smile = true
let test = () => {
if (smile == true) {
document.getElementById("image").src = "path of picture2";
smile = false
} else {
document.getElementById("image").src = "path of picture1";
smile = true
}
}
</script>
whenever I click the button the browser shows me picture2 then if I click again shows me picture1 and this can be done over and over again please share your solution for this
Solution
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.
let img = document.querySelector('[data-smile]');
img.onclick = () => {
img.dataset.smile = img.dataset.smile == "true" ? "false" : "true";
img.src = img.dataset.smile == "true" ? "https://i.imgur.com/jgyJ7Oj.png" : "https://i.imgur.com/PqpOLwp.png";
}
<div>
<img src="https://i.imgur.com/PqpOLwp.png" data-smile="false">
</div>
Hope that helps :)
Answered By - HackerFrosch
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.