JavaScript Click Event Tutorial: Toggling a Light Bulb

JavaScript Click Event Tutorial: Toggling a Light Bulb

JavaScript Click Event Tutorial: Toggling a Light Bulb

  • CodeCamp Admin

  • 3 minute read

Are you interested in learning how to toggle a light bulb on and off using JavaScript? Look no further! In this tutorial, we will walk you through the process step by step.

First, let's start by understanding the basics. The original CodePen we will be working with can be found at CodePen Starter Code: https://codepen.io/precodecamp/pen/gOENJyN . This exercise is a great way to practice your JavaScript skills and learn how to manipulate elements on CodePen.

Starter Code:

CodePen Starter Code: https://codepen.io/precodecamp/pen/gOENJyN

To begin, we need to identify the element that controls the glow of the light bulb. In this case, the class 'bulb' is responsible for the background color and the box shadow. By commenting out the background color, we can see that the glow remains. This means that the box shadow controls the glow.

Next, we will use JavaScript to select the 'bulb' class and make changes to its styles. We will create a global variable to track the state of the light, which is initially set to 'on'. We will also create a function to toggle the light on and off when the light bulb is clicked.

To add a click event to the light bulb, we can use the document object model. By referencing the 'bulb' class and assigning it an onclick event, we can call our toggleLight function when the light bulb is clicked.

Inside the toggleLight function, we will check the current state of the light. If the light is on, we will update the background and box shadow to turn off the light. If the light is off, we will update the styles to turn on the light.

By changing the opacity of the background to 0.1 and adjusting the box shadow, we can create the effect of a toggled light bulb. The global variable 'isLightOn' will be updated accordingly to reflect the current state of the light.

With just a few lines of code, you can now toggle a light bulb on and off using JavaScript! Feel free to check out the full code and demo on the CodePen link provided.

Completed Code:

CodePen Completed Code: https://codepen.io/precodecamp/pen/QWoXRoN

Learning More

If you're interested in learning more about JavaScript fundamentals and other programming concepts, we invite you to schedule a meeting with PreCodeCamp's admissions team. Our experienced instructors are ready to guide you through the learning process and help you build a strong foundation in coding.

Don't miss out on this opportunity to expand your skills and embark on a rewarding coding journey. Schedule a meeting with our admissions team today!

Like and subscribe to our channel for more tutorials and coding tips. We look forward to seeing you in our next video!