Skip to content
Related Articles

Related Articles

Turn on or off bulb using JavaScript

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 19 Feb, 2019

Write a JavaScript code that turns ON and OFF the Light Bulb.

img src = URl
img src = image_name.jpg

Here the src property sets or returns the value of the src attribute of an image. The required src attribute specifies the URL of an image.
There are two states of the bulb is used which are specified below-
Initial state of bulb (OFF STATE):

After clicking on bulb (ON STATE):

JavaScript code to illustrate this topic:

    <!-- onclick event is generated
        and it calls turnOnOff function -->
    <!-- OFFbulb.jpg is the turn off bulb image -->
<img id="Image" onclick="turnOnOff()" 
    <p>Click on the bulb to turn it ON and OFF</p>
     // implementation of turnOnOff function -->
     function turnOnOff() 
     // taking image in image variable
     var image = document.getElementById('Image');
     //Match the image name
     //whether it is ONbulb or OFFbulb
     //change image to OFFbulb.jpg if
     //it match with ONbulb otherwise
     //change it to ONbulb.jpg -->
     if (image.src.match("ONbulb"))
         image.src = "
         image.src = "

Before clicking on the bulb-

After clicking on the bulb-

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!