Event Listeners

Back to Curriculum Index


  • 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!

Event Listeners

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.

In JavaScript, an event listener is a way to set up code to run only when a very specific thing happens. You want to change the color of something when the mouse is in a specific place? Great! That’s an event listener – you’ll tell the code to listen for the mouse to be on a specific element on the page, then run the code that changes the color.


Let’s look at this example of an event listener and talk through the pieces:

See the Pen Event Listeners Example by Try Coding (@turing-trycoding)on CodePen.

Applying What We’ve Learned

Try It: Changing HTML with JavaScript

Back in your own Puppy Facts CodePen, add a button in the HTML.

Write code in the JavaScript pane so that when the button is clicked, the title of the webpage changes to a different topic!

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!

Here's a CodePen you can start with!

🌶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.

Wrap Up