Search code examples
javascriptbooleanelementsrc

How to turn a lightbulb on and off in JavaScript?


I am making a function in javascript that is supposed to change the src of an html element to make it seem like the html element (a lightbulb) is turning on and off. It includes an if else if statement to check whether the bulb is already off or on and then turns it to the opposite. The function is set off by a button.

My problem is that when I click on the button it turns the bulb on, but when I click it again it turns off. Why is this happening? I am getting no error messages from the console.

Here is my code:

<!DOCTYPE html>
<html>
<head>
  <style>
    button {
      background-color: white;
      border-radius: 0.25px;
      border-color: black;
      height: 30px;
     }
   </style>
 </head>
 <body>

   <button id = "button" onclick="light(on)"></button>

   <img id="myImage" src="file:///C://Users/xenia/Downloads/light-bulb-off- 
 pixilart.png">

   <script>
     var on = 0; // 1 is true, 0 is false

     function light(on) {
       if (on == 0) {
         document.getElementById("myImage").src="file:///C://Users/xenia/Downloads/ligh
         t-bulb-on-pixilart.png"
         on = 1
        }
        else if (on == 1){
          document.getElementById("myImage").src="file:///C://Users/xenia/Downloads/ligh 
         t-bulb-off-pixilart.png"
         on = 0
       }
      }
    </script>
</body>
</html>

Solution

  • You are using a global variable, but you hand over a value for a local variable inside of the function. Then changing of this variable does not affect the global value, because primitve values are handed over by value.

    You need to change this line into (without on)

    <button id = "button" onclick="light()"></button>
    

    and the function signature, without a variable

    function light() {
    

    Now you access the global variable on and change the value.


    Just another hint, you could take a boolean value (true or false) and omit the check in the if statement by using the variable directly and omit the second check, because you have only two values.

    Maybe you could omit the second check with a number value, because you have no code which assigns a different value than 0 or 1.