Written by Siddartha Thota on August 8, 2014 in JavaScript

JavaScript: Turn-on and Turn-off light [onClick Event]

GET ALERTS:

Get our Latest updates delivered to your mailbox!

This is a very simple JavaScript tutorial. In this tutorial, we will be discussing about how to turn-on and turn-off the light of a bulb. The logic is pretty simple over here. We are not doing some rocket-science. We are just taking couple of images

  1. First Image – Bulb 1 (turn-off state)
  2. Second Image – Bulb 2 (turn-on state)

We will bind the Bulb 1 with the on-click event of Javascript and then we will change the image to the other (turn-on and then turn-of and vice versa), everytime you click on them.

So, lets not waste any time. Jump into the action right away. You can download the source code from here.

Download Source Code


<!DOCTYPE html>
<html>
<title>Tutorial to turn on/of light</title>
<body>
<script>
function action() {
 var image = document.getElementById('bulb');
 if (image.src.match("bulbon")) {
 image.src = "bulboff_image.gif";
 } else {
 image.src = "bulbon_image.gif";
 }
}
</script>

<img id="bulb" onclick="action()" src="bulboff_image.gif" width="150" height="230">

<p>Click the bulb to turn on or off the light</p>

</body>
</html>

Output Images:

turnedoff light

turnedon light

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: