'Splain Like I'm Five: JavaScript Events
Tags: javascript, webdev, programming, beginners
Published: 2022-02-23 22:03:42

It is safe to say that the heart and soul of any effective web page is the ability for a user to functionally interact with the contents of that web page. Being able to click on, scroll through, or input information through a web browser is fundamental to the usability of most modern-day web applications--from social media, to banking, to learning software engineering through an online bootcamp. But what exactly is going on under the hood when you click that like button, anyway? The answer to that question is: [A JAVASCRIPT EVENT](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events)! 

Javascript events describe a multi-process coding cycle that involves three major components: HTML Elements, Event Listeners, and Event Handling Functions. Let's dig in to how these three components work together to create an enriching, interactive experience for your user!



**HTML Elements and the DOM**
As you may know, the elements you see on a web browser are structured by HTML. Each [HTML element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element) has a specific purpose in the HTML document, and therefore the structure of the web browser. For example, if you'd like to add a "like" button to your page you would first craft its structure in the HTML document as an element. However, these HTML elements are static unless we use javaScript to animate them, which are then rendered in the [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model).



**Javascript Event Listeners**
Unless you use javaScript to tell the browser what to do with that "like' button once its clicked, that like button will be nothing more than a fancy icon decorating your browser with no real functionality. So how do we create a line of communication to the HTML document to animate our like button? Luckily, javaScript has a built-in system for "listening" for events! Simply put, an "event listener" is a built-in javaScript command that links an HTML element to the event you would like to have happen. This is done in three steps: 

1. "Grabbing" the HTML element from the document with a [query selector](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) and attaching it to a constant variable.

```
const likeButton = document.querySelector("button"); 
```

2. Linking that constant variable to the event you would like to enact using [.addEventListener()](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener).

```
likeButton.addEventListener("click", );
```

3. Referencing the "Event Handler" function in the event listener that will ultimately enact the event we want once it's called. 

```
likeButton.addEventListener("click", handleLikeButton);
```



**Event Handlers**
Hold up, we referenced an event handling function with the event listener we just learned about! What's going on there?? The "event handler" is an important piece of this puzzle, because we need to tell our program what to do with the 'click' we just assigned in our listener using a [function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions). An event handler is a callback function that indicates to the listener what the outcome of the event will be. For example: 

```
function handleLikeButton(){
  likeNumber.textContent = ++likes
}
```

In the above case, we've created a function that incrementally (_++likes_) increases the displayed (_text content_) number of likes (_likesNumber_) on our page! The event handler dictates the outcome of the event. The handler is called by the event listener--which links it to the 'click'--and increases the likes once the click is initiated.   
 
Here's visual of how the components of the javaScript event cycle work together: 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t25yp9fevdm3woxoe4kx.png)



**Types of Events**
As you can imagine, click events are one of many, MANY javaScript events that can be applied to a webpage. Other common events include: 

<u>Mouse events</u>: Any interaction having to do with mousing over, in/ out of, or clicking on an element.

<u>Keyboard Events</u>: Any interaction having to do with key presses of any kind.

<u>Submit Events</u>: Events pertaining to inputting and submitting values to forms. 

<u>Screen Sizing Events</u>: Events that occur when resizing or scrolling through the browser window. 

And many [more.](https://developer.mozilla.org/en-US/docs/Web/Events#standard_events)



**Event Objects**
Event objects are a way for you to call on the event in a handler as a [parameter](https://developer.mozilla.org/en-US/docs/Glossary/Parameter). Common usage for this would be to change specific properties of the event target (In our case, the LikeButton variable we grabbed from the HTML sheet): 

```
function handleLikeButton(e){
   console.log('e: ', e.target);
    } 
```
The target property of the event object is a reference to the element the event occurred upon. So, in the above example, we are logging the content of our like button to the console. Other uses for this method would be to modify the qualities of the event target (like the color or text content), or to link the event target to a database object (and many more).  Event objects can be labeled in any way, but conventionally they're labeled "e", "evt", or "event" because they're short and easy to remember, plus it's always good to be consistent in shared code. 



**Bubbling and Capturing**
Sometimes you'll want to link an event listener to a parent node that oversees multiple HTML elements with their own events. This can be super handy, like when we have lots of buttons on one page nested under the same parent node and only want to take the time to write out one event listener, or to link multiple events under the same parent node. 

_"Capturing"_ is a phase in the DOM's order of operations where the browser reads our code from the outermost layered node in the DOM tree, to the innermost. In this phase, the browser is "listening" for events starting from the top down.

_"Bubbling"_ is essentially the opposite of the capturing phase, and starts _at the time the event is triggered_. The inner-most nested node is triggered first, then its parent node, grand parent node, and so on all the way back to the top of the document. If events are linked to these respective nodes the events will be triggered in order from the innermost nested event out to the top. It's important to note that modern browsers handle events in the bubbling phase by default. 

Here is a diagram of the Capture/Bubble cycle: 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rizadpjcmub2bkxpztzo.png)
  
You can read more about the Capture/Bubble cycle _[here](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events)_.



**Stop Propagation**
 There are times where bubbling can be detrimental to to the functionality of your page. One scenario is when two events firing in tandem with each other negatively effect the outcome of one or all of the events. Luckily, there's a way to "stop the propagation" of the bubbling phase! It's called, naturally, "[.stopPropagation()](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation)". 

Best practice is to call .stopPropagation() on the event object in your event handler, which will stop the bubbling phase at the time the event is called. When invoked on a handler's event object, .stopPropagation() makes it so that first handler is run but the event doesn't bubble any further up the chain. 

An example of .stopPropagation() syntax: 

```
likesBttn.addEventListener("click", function (event) {
    event.stopPropagation();
    likeNumber.textContent = ++likes
    
  });
```


**Prevent Default**
A default action of a submit form event is to reload the browser. In some cases, we want to prevent that default action. Luckily, javaScript has a built-in command to deal with this issue: [.preventDefault()](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault). Having this command included in your event handler function creates a catch-all scenario for those circumstances when you don't want the browser to automatically refresh the form.

Here's an example of .preventDefault() syntax in the context of a form event: 

```
function handleReviews(e){
  e.preventDefault()
  let reviewLi = document.createElement('li')
  reviewLi.textContent = `${reviewInput.value}

  e.target.reset()
};
```

In the above example, we've created an event handler that handles a form for users to add new reviews to our page! The event object is referenced, then we use [dot notation ](https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781) to add the preventDefault() command to it. The rest of the code displayed here allows us to add a new HTML element with our users new review to the DOM, and reset our review form input fields for the next user! 



**Conclusion**
Events are hugely important to creating an interactive, functional web page. The options for how to deploy events and their handlers are endless, and there are many "best practices" to look for when planning your event cycles, depending on what events you'll be including on your page. Events exist in many coding languages and javaScript is only one of many iterations of this process in the field! The more you learn about events--and there is much, MUCH more to learn!-- the more empowered you'll be to make effective, functional, interactive web applications to attract users. 

Happy eventing! 

**Resources**

- [_MDN: Event reference_](https://developer.mozilla.org/en-US/docs/Web/Events#standard_events)
- _[MDN: Introduction to Events](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events)_
- _[The 3 Phases of Event Propagation in JavaScript Explained](https://javascript.plainenglish.io/the-3-phases-of-event-propagation-explained-f76348b5343f)_
- _[What is event capturing and event bubbling](https://haruncsebd.wordpress.com/2011/10/01/what-is-event-capturing-and-event-bubbling/)_
- _[MDN: Stop Propagation](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation)_
- _[MDN: Event Prevent Default](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)_
- [JavaScript Quickie— Dot Notation vs. Bracket Notation](_https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781)
- _[MDN: HTML Elements ](https://developer.mozilla.org/en-US/docs/Web/HTML/Element)_
- _[MDN: Query Selector](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector)_
- _[MDN: Add Event Listener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)_
- _[MDN: Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)_
- _[MDN: Parameters](https://developer.mozilla.org/en-US/docs/Glossary/Parameter)_