Open In App

Turn on or off bulb using JavaScript

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In this article, we are going to learn how to turn on or off bulbs using JavaScript.

Syntax

<img src = "URl" onClick=turnOnOff()>

Approach

  • The HTML file includes the necessary structure with a <script> tag for JavaScript code, a <img> tag for the bulb image, and a <p> tag for a descriptive message.
  • There is a JavaScript function named turnOnOff() defined within the <script> tag. This function toggles the bulb image between ON and OFF states based on its current source.
  • The <img> tag has an id attribute set to “Image”, and its src attribute is initially set to the OFF state image URL.
  • The turnOnOff() the function is invoked when the bulb image is clicked (onclick="turnOnOff()"). This handles the toggle functionality.
  • Inside the turnOnOff() function, the current source of the image is checked. If it matches the source for the ON state, the image is switched to the OFF state, and vice versa.

Example: In this example, We are following the above-explained approach.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,
                   initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
    <script>
        function turnOnOff() {
            let image = document.getElementById('Image');
            if (image.src.match("ONbulb"))
                image.src =
            else
                image.src =
        }
    </script>
 
    <img id="Image" onclick="turnOnOff()" src=
 
    <p>
        Click on the bulb to turn it ON and OFF
    </p>
</body>
 
</html>


Output: 



Last Updated : 03 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads