GOAL: Today we are going to add event listeners to our web pages in order to create an app that:
- Turns a light on and off when clicked.
- Tracks how many times we have clicked the lightbulbs.
When a lightbulb is "on" it has a class of "active" which colors it white. When the lightbulb is "off" it does NOT have a class "active", so it is colored black.
<!-- Lightbulb on -->
<div id="lightbulb1" class="item lightbulb active">💡</div>
<!-- Lightbulb off -->
<div id="lightbulb2" class="item lightbulb">💡</div>In order to add or remove a class, we can use the .classList.toggle("CLASS_NAME") method 🔍. This command contains two key parts:
- The
.classListcommand returns the list of classes currently attached to a DOM element. - The
.toggle()method checks if a specified class is currently present. It will then either add or remove this class name based on whether it is present or absent.
Therefore, for a lightbulb, we can toggle "active" by doing
myBulb.classList.toggle("active");- Connect your
script.jsfile to yourindex.htmlusing a<script>tag. Console.log a message to verify that it works! - Use
document.querySelectorto select for each of the three lightbulbs. Store each in it's own variable. - Use
document.querySelectorto select theh3 class = "subtitle". Store this in a variable. - Create a variable called
countwith an initial value of 0. This will track how many times you have clicked the lightbulbs. - For each lightbulb, create an
addEventListenerthat responds to a"click"event. - Every time the lightbulb is clicked you should:
- Increase
countby 1. - Output the new
countto theh3 class = "subtitle"in the form ofYou've clicked the lights COUNT timeswithCOUNTreplaced by the currentcountvalue. - Toggle the lightbulbs classList of
"active". Thus, if the class of"active"is currently present, then it should be removed and vice versa.
myBulb.classList.toggle("CLASS_TO_TOGGLE");
- Increase
- Currently it says
"You've clicked the lightbulbs 1 times"when you click the lightbulb the first time, but that grammar isn't correct. Create a conditional statement that makes this singular whencountis 1 and plural for all other values ofcount. - Rewrite this code to make any object active if your mouse has entered the object. Then add functionality for if your mouse exits the object.
- Research how to use
document.querySelectorAllto select all the lightbulbs rather than writingdocument.querySelector()three times. - CHALLENGE PUZZLE: Add more bulbs to the page and get one bulb to turn off multiple bulbs. For example, if you click bulb 1 it alters the class of bulbs 1, 2, and 5.
