Skip to content
Advertisement

How to toggle the “src” attribute of an image without using an if-statement?

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.

let smile = true  
let test = () => {
   if (smile == true) {
     document.getElementById("image").src = "https://images.freeimages.com/images/large-previews/adb/fruit-in-a-bowl-1637721.jpg";
      smile = false
    } 
 else {
     document.getElementById("image").src = "https://images.freeimages.com/images/large-previews/a33/fresh-red-ripe-strawberries-1641723.jpg";
     smile = true
    }
}
 <img id="image" src="https://images.freeimages.com/images/large-previews/a33/fresh-red-ripe-strawberries-1641723.jpg" width="160" height="120">
 <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.

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 🙂

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