JS: Intro to Event Listeners

Learning Goals

  • Continue to develop a basic understanding for JavaScript syntax
  • Understand how to attach event listeners to DOM elements
  • Understand how to write event handler functions

Vocabulary

  • Event Any event which takes place in the DOM, these can be generated by users or the browser.
  • Event Listener A function invoked on a DOM node which fires the event handler when a specified event occurs on the node or its children
  • Event Handler A function that will run when a specific event occurs

Warm Up

Complete the tasks listed in the JS file on this codepen.

Event Listeners

Changing stuff on the page with JavaScript is great, but you might as well have just written it in the markup to begin with. The real power of JavaScript comes into play when we write code that responds to user input.

This power emerges when we start listening for user events. This is the crux of front-end engineering. We present a user interface and then as the user interacts with the UI, we change and update what they see.

Let’s revisit the codepen from the Warm Up and add in an Event Listener.

Talk It out

Take turns with your partner talking through the code found here. Practice using technical vocabulary. It’s okay to mess up! This takes practice. If you need help, look below!

Need help talking through the code?

  1. We’re querying for all of the elements we need and we’re storing them in variables.
  2. We’re adding an event listener to the <button> with the class of .change-text.
  3. We’re passing addEventListener() two arguments:
    • The type of event we’re interested in listening for.
    • The name of a function that should be called whenever that event happens.
  4. We declare the function that will be called when the button is clicked.

Explore

Open up a webpage that you often visit. Maybe it’s a social media page, maybe it’s your bank’s website, maybe it’s a news site. Take a few minutes and list all the event listeners that you think might be on that page! What do they do?

Style Change on Button Click

Like we mentioned earlier, it’s pretty common for a user to experience helpful feedback from an application after they’ve taken some sort of action.

Take for example the “heart” icon on CodePen. CodePen has 4 levels of “love” - 0, 1, 2, and 3. Each time a heart is clicked, the user increments their love up by one. (Until the click when it is read and at level 3 - at that point, it goes back to 0). While the “love leveling” is a bit confusing, this is still a great example of styles changing based on user interaction.

To do this, we need to combine what we just learned about event listeners with what we learned about changing styles programmatically earlier this week.

Pair Challenge

We are putting a few pieces together now, so this may seem a bit more challenging. That’s when it is especially important to pseudo-code, or write human-readable notes that give you a roadmap for the code you will later write.

You will be building off of this Codepen to create a single div that is gray. Then, when it is clicked, it turns pink!

In your notebook:

  • List the directions, as specially as possible, that you want to give to the computer.
  • What are the DOM elements that this program will need to know about? What variable names will you use for them?

Now, implement your ideas in code.

Extra Time?

If you have extra time, think about and pseudcode what you would need to do to build out the full CodePen heart:

  • when clicked, the gray div turns pink
  • then on another click it turns deeper pink
  • then when clicked again, it turns red
  • then when clicked again, it returns to being gray

Now, get together with another group and discuss your approaches. This is not a time to share “solutions” or “answers”, but instead to talk about how you went about breaking down the problem. Did you pseudocode? Did you look up any documentation? What did you google?

Get User Input

We can use the .value property available on an input DOM element to get the value that a user has typed into it.

Explore

Follow the steps below to explore how .value works!

  1. Open your dev tools and inspect this box, specifically, the input field below. What is its class name?
  2. In the console, call document.querySelector('.check-me');
  3. In the console. call document.querySelector('.check-me').value;
  4. Type your favorite food into the input
  5. In the console. call document.querySelector('.check-me').value;

When called, the .value property on an input element will return the current value.

One of the top misconceptions/mistakes we see students make while in Mod 1 is attempt to capture the value of an input while the input is empty. If you want to get a user’s input, we have to get the value inside of some event listener - on an event that happens after the user has typed into the input field.

Below is an example of a small application that takes a user input, then changes the color of a box based on that input:

See the Pen Color Box by Turing School (@turing-school) on CodePen.

Let’s break down what’s happening in the CodePen above:

  • Lines 1-3: Declare variables for the DOM elements that we will need (box, input field, button)
  • Line 5: Attach an event listener to the button
  • Line 7: Declare a function that will execute when the button is clicked
    • Declare a variable, color that takes the value the user selected and stores it
    • Applies an inline style, backgroundColor with that newly selected color

Anonymous and Helper Functions

Paired Practice

Examine this code and talk about the following questions:

  1. Why do you think “Summer” is appearing in the screen, when “Fall” is in the original HTML?
  2. Why isn’t the button working?

Remember that the second argument the addEventListener accepts is a function name, not an invoked function. This presents challenges when we need to pass parameters to that function. There are two options for how to approach this issue.

You can use an anonymous function:

button.addEventListener('click', function() {
  changeSeason('fall');
});

Or you can use a helper function:

button.addEventListener('click', updatePage);

function updatePage() {
  changeSeason('fall');
}

Both approaches have pros and cons. Helper functions can seem like too much code for a simple issue, while too many anonymous functions can lead to unclear and hard to follow code. The important thing to remember is that you should only be reaching for one of these options when you need it. If there are no arguments to be passed in, you don’t need a helper function or an anonymous function.

Suggested re-teaching practice

When you study event listeners, here are some suggested exercises:

  • Look up what some common event listener types are (you’ve already seen click!)
  • Read up on the event listener documentation
  • Create a codepen with some HTML elements, and make up some event listeners for them! Try turning a red square green when it gets clicked. Try getting the data from an input field and displaying it on the page.
  • In Codepen, create a simple webpage with a night-mode toggle button!

Lesson Search Results

Showing top 10 results