Ask coding questions

← Back to all posts
simple if question
ricardoda (2)

hello,
I am a rockie in frontend.
I made this code, when the button receive a click, it changes the state(estado1) from on to off. It is working :)
Now, I need create a function when estado1 is with "on", I want it shows one img. I will put more buttons like this, then when button one two and three are "on" it shows one image. when the button buttons 4,5,6 is on another image into a Div in html code. I tryed it with simple if but I didnt get it. sorry for this basic question and thank you for your time.

<script> var onoff1 = document.getElementById('onoff1'); var estado1 = document.getElementById('estado1'); onoff1.addEventListener('change', function() { estado1.innerHTML = this.checked ? 'on' : 'of'; }); </script>
<html> <div> <input type="checkbox" class="toggle" id="onoff1"> <label for="onoff1"></label> </div> <p id="estado1">off</p> //when click it is working and change to on </html>
Commentshotnewtop
heyitsmarcus (287)

I made a Repl where you can toggle the checkbox on and off, and it changes the image between two different urls. You can make this more dynamic and extend it from there, as well. All I did was added in an img element and give it the default src (since it starts as "Off", I set the image default to the "Off" source). So, when you click it, it will change between on and off in the label and image. I gave the image the id of "estado1" since it is showing the state of the image.

I hope it helps, Ricardoda!

https://repl.it/@heyitsmarcus/Ricardoda-code