JavaScript: Event Listeners made easy
Tags: javascript, webdev, beginners, dom
Published: 2022-07-13 02:14:53

Looking for a beginner-friendly example? Skip to the end.

## Why am I writing this?

If you are not already an expert programmer, digesting a new concept is often daunting. There is no way around the fact that it takes time and effort for the next topic in your learning journey to sink in. This is further compounded by the fact there are many places to search for help and they are all wrapped in their own assumptions, intentions, and shorthands. It is often said that _Googling_ is an important skill to develop--and it absolutely is!

Equally important however, is at this stage we must realize some sources are more helpful than others. If you have been programing for weeks or months, the Mozilla Developer Network (MDN) is not the best place to go to initially understand a foundational concept. A colleague of mine put it best. MDN is a great place to go when you want to have "beard-stroking, programming philosophizing time." It is a great place to get exhaustive, 100% technically correct answers but the target audience is not beginners. If you are new to event listeners [this explanation may not help you](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener).

If you are a true beginner looking for help on an assignment or if want to see a basic example of a concept, you likely do not care about all of the optional parameters of a method or function. Nor do you particularly care about the technical constraints of this particular built-in JavaScript method versus a similar looking built-in method. So let me be clear about the intentions of my blog post. If you want to start making richer webpages _now_...I give you: **Event Listeners Made Easy.**


## Let's begin: what is an Event Listener? 
The cool thing about programming is that you can often think through tasks verbally and literally. It is important to remember that we humans are the smart ones and the computers are the dumb ones. The syntax to create an event listener is `.addEventListener()`.

This is a `method` built into `JavaScript` by our programming predecessors, very kind of them. They were even kind enough to give `.addEventListener()` a very _meaningful_ name and syntax. If we stop and think through this literally: 
1. We are **adding** an "Event Listener" to something.
2. We are indicating that we are **listening** or waiting for a certain **event to happen to** our something.

Typically, we are adding this "Event Listener" onto a `HTML element` inside the `document` in the DOM. Let's talk through a basic example:

1. We target a specific `HTML element` in the DOM
2. We apply the `method` `.addEventListener()` to our `HTML element`
3. We then want to pass 2 arguments into `.addEventListener()`
4. The first argument is the type of event we are looking for (i.e. `"click"` to listen for a mouse click, `"submit"` to listen for a form submission etc.)
5. The second argument is the `function` or the work we want to kick off once our specified event happens to our `HTML Element`.

In general, a basic `.addEventListener()` setup has two parameters (yes there are additional optional parameters if you check MDN). A high level example looks something like this:
`some HTML Element` `.addEventListener`(`"name of event"` ,` some function`)

Example recognized events are: `"click"`, `"keydown"`, `"keyup"`, `"keypress"`, `"submit"`, `"mouseover"` etc. Again, we owe a debt to our programming predecessors. They already equipped `JavaScript` with the ability to recognize when common mouse and keyboard actions occur.
Let's look at a real example now.

## Example code
Suppose you have the following `HTML` code in your DOM:
```
<div id ="info">
     <button id="example-button">Click Me!</button>
</div>

<--! This is merely a <button> HTML element that will --> 
<--! read "Click Me!" when rendered in a web browser -->
<--! and the button is nested inside a <div> element -->
```
This button is not very useful right now. Sure it appears on our webpage but it is missing _behavior_. When you click this button it will not do anything. To add _behavior_ to an `HTML element` we apply the `.addEventListener()` `method` to our `HTML element` using `JavaScript`.

Let's write some `JavaScript` code to achieve this. For a quick review, we first need to target the `HTML element` in our DOM that contains our button using `.querySelector()` or `.getElementById()`. I will use `.querySelector()` just to demonstrate how specific you can be with your query. Yes we can use `.getElementById()` with less code in this example. 
```
let buttonElement = document.querySelector("div#info button")

// This line of code targets our <button> HTML element
// that is nested inside that parent <div>
// and stores it in variable buttonElement.

buttonElement.addEventListener("click", () => {
   console.log("You Clicked The Button!")
   console.log("If you see this, your Event Listener works!")
})

// Here, we added an Event Listener onto our HTML button
// and specified the "click" event as the 1st argument.
// As the 2nd argument we passed in an anonymous function
// using arrow syntax. The function we passed in this case
// has no name or parameters. They are not explicitly necessary
```
We have just done something very powerful. We took some **static** HTML and made it **dynamic**. Now when we click that "Click Me!" on our webpage i.e. when we click on this button:
```
<div id ="info">
     <button id="example-button">Click Me!</button>
</div>
```
we can specify to make some code to run. Inside the `.addEventListener()` we wrote, we specified instructions that will run after our button is clicked. The `anonymous function` passed inside as the 2nd argument will trigger and simply print to the `console` "You Clicked The Button!" and "If you see this, your Event Listener works!" but that is already a beautiful start. We could make that `function` much more robust. We could name and define a more complex `function` in the `global scope` and pass it into our `.addEventListener()` as the second argument. We could have that more robust `function` specify instructions to append some new information into our DOM once our webpage user clicks our button. We could even specify instructions to send data to a server and have that data persist in the server once our button is clicked even after we close our webpage. But for now, we have event listeners working and that is a victory.

You now understand the syntax and the basic parameters of `.addEventListener()` and can start to add `"click"` events to your `HTML Elements` in the DOM.