- Understand the concept of an event listener
- Attach an event listener to a button
- Continue building a developers mindset by breaking code and being ok with it!
Imagine that you’ve just ordered food from GrubHub and are waiting for it to arrive. When the doorbell rings, you’ll stand up from the couch, walk over to the door, open it, and take your food. Guess what? You programmed yourself with an event listener.
Let’s look at this example of an event listener and talk through the pieces:
Earlier, we talked about the mindsets developers must have to be successful: a growth mindset, demonstrated by being curious, resourceful, communicative, and not being afraid to question how things work.
We’re going to take a few minutes to really “break” this code to build a deeper understanding of how it’s working. If you’ve had that feeling of “I think I get it, but I couldn’t recreate it” or “I basically get this… but if I had to identify one little error, I’d struggle to find it on my own”, you are not alone.
When we “break” code, we are engaging in a process of tinkering with it to better understand it. To identify which piece of code plays which role in the functionality, it’s important to only break one tiny thing at a time!
- Bring back lines 2-4, now remove line 5. What happens?
- Bring back line 5. Remove lines 8-12. What happens?
- Why isn’t the image changing? Look at line 3 in HTML and line 5 in JS to see if you can identify the problem.
Applying What We’ve Learned
Back in your own Puppy Facts CodePen, add a button in the HTML.
If you complete that with extra time, change the text in the
p tags so that when the button is clicked, the facts match your new topic!
🌶Click here for a Spicy Challenge🌶
Wouldn't it be nice if the user could toggle back and forth between Puppy Facts and your other facts? Add another button, then implement the code to make this happen.