JavaScript Events: Simplified
Tags: javascript, beginners, events, eventlisteners
Published: 2022-10-14 17:31:49

When I started learning JavaScript, The first concept that I really struggled with was JavaScript Events. As a result of my experiences with JavaScript events, I wanted to create a blog simplifying JavaScript Events, how to listen for them, and how to respond to them. 

## What are JavaScript Events?

To begin, JavaScript is able to listen for events happening in the browser. These events can include but are not limited to Keydown, Form Submission, Mouse Click, Mouseover, on-change, mouse-enter, focus, blur etc. In order to listen for these events, and to respond to these events, one can utilize the addEventListener() method.

## addEventListener() Method

.addEventListener() is a method in JavaScript that can be used to listen for and respond to events happening in the browser. The method takes in two arguments:

Argument 1: the type of the event we are _listening_ for (eg. "click", "submit" etc.)

Argument 2: A callback function that _responds_ to the specified event in a specified manner. 

## Steps to using .addEventListener()

In order to use .addEventListener() we must:

1. Grab the element that we want to add an event listener to and save the element as a reference in a variable.
2. Add the .addEventListener() method to the variable containing the element of interest. 
3. Pass the event type and a callback function as the arguments to the addEventListener() method

## Step 1: Grab the Element of Interest

The following methods can be used to grab the element of interest:

**document.getElementById()**

Note: This method will return the element with the requested Id. This method is the most specific method since all Ids are unique to their own elements.

example:


```
//the HTML Element we want to add an event to
<button id="button" className="btn"></button>
```

```
//Using, document.getElementById(),I entered the id of the button in the parenthesis, added quotations marks to the id, and saved the element to a variable called buttonById
const buttonById = document.getElementById("button")
```

**document.getElementsByClassName()**

Note: This method will return a list of elements with the specified class name. This method is not recommended when we are looking to grab a specific element.

```
//the HTML element we would like to grab
<button id="button" className="btn"></button>
```

```
//used document.getElementByClassName, inserted the className into the parenthesis, and assigned the element to a variables called buttonByClass
const buttonByClass = document.getElementsByClassName("btn")
```

**document.getElementsByTagName()**

Note: This method will return all elements with the specified Tag Name. This method is the least specific and is not recommended when we are looking to grab one specific element.

```
//the HTML element we would like to grab
<button id="button" className="btn"></button>
```

```
//used document.getElementsByTagName(), passed the Tag Name surrounded by quotation marks, and assigned to a variable called buttonByTag
const buttonByTag = document.getElementsByTagName("button")
```

Other methods include CSS Selectors such as:
**document.querySelector(selector)**

document.querySelector will return the first element that matches the requested selector. querySelector can be used to grab an element by its Id, Class Name, and Tag Name.

If we look at the following HTML elements

```
<button id="button1" className="btn">button 1</button>
<button id="button2" className="btn">button 2</button>
<button id="button3" className="btn">button 3</button>
```

To grab the first element by its id using querySelector, we need to pass a # into the parenthesis followed by its Id.

`const buttonQueryId = document.querySelector("#button")`

To grab the first element by its Class Name using querySelector, we need to pass a . into the parenthesis followed by its className.

`const buttonQueryClass = document.querySelector(".btn")`

To grab the first element by its Tag Name using querySelector, we need to simply pass the Tag Name with quotation marks.

`const buttonQueryTag = document.querySelector("button")`

**document.querySelectorAll(selector)**

document.querySelectorAll() will return a nodeList of the elements that match the criteria of the selector. The method grabs elements by their Class Name and Tag Name.

For example, 

```
<button id="button1" className="btn">button 1</button>
<button id="button2" className="btn">button 2</button>
<button id="button3" className="btn">button 3</button>
```
to grab elements by their class:
`const buttonsClass = document.querySelectorAll(".btn")`

to grab elements by their div:
`const buttonsTagName = document.querySelectorAll("button")`


To learn more about the above two methods, visit this [website](https://www.w3schools.com/jsref/met_document_queryselector.asp).

## Step 2: Add the addEventListener() method

We can add the .addEventListener() method to the variable names that contain our HTML Element/s of interest.

example:

```
//.addEventListener() to a button we grabbed using getElementById and saved to a variables called buttonById

buttonById.addEventListener()

//.addEventListener() to a button we grabbed using querySelector and saved to a variable called buttonQueryClass

buttonQueryClass.addEventListener()

//.addEventListener to buttons we grabbed using querySelectorAll and saved to a variable called buttonsTagName 

buttonsTagName.addEventListener()
```

## Step 3: Pass in the arguments

Now we can move on to the final step, which is passing in the arguments. 

**Click Event**

For example, if we want add a **click event** to our button with a call back function that will console.log "hello" for every click, we could write: 

```
//the HTML Element we want to click
<button id="button" className="btn"></button>
```

```
//step 1: grab the element

const buttonById = document.getElementById("button")

//step 2: add the .addEventListener() method 
//step 3: pass in event type and callback function as arguments

buttonById.addEventListener("click", myCallbackFunction) 

//the callback function that will console.log "hello"

function myCallbackFunction(){
   console.log("hello")
}
```

**Form Submission**

If we want to add an event listener to a form which will console.log "hello" every time it is submitted:

- We must add an eventListener to the <form></form> element instead of the button element

- We must use "submit" as our event type 

- We must add event.preventDefault() in the callback function to prevent any default behavior of the form  

For example, 
```
//basic HTML form 
<form id="form">
  <label for="username">Username</label>
  <input type="text" id="name" name="name" />
  <button type="submit">Enter Username</button>
</form>
```

```
//step1: grab the element

const form = document.getElementById("form")

//step2:add .addEventListener() method+ pass in the arguments

form.addEventListener("submit", myCallbackFunction)

function myCallbackFunction(event){
   event.preventDefault()
   console.log("hello")
}
```

## Conclusion

I hope this serves as a beginner's guide to understanding the very basics of JavaScript events. JavaScript events can get more complex, especially the callback functions. I kept the callback functions very basic -console.log("hello")- due to this complexity. Callback functions deserve their own separate blogs or two! 

**To learn more about Callback functions, visit:**
[What are Callbacks in JS and How to Use Them](https://dev.to/smileyshivam/javascript-callback-functions-what-are-callbacks-in-js-and-how-to-use-them-123o)
[event.target JavaScript](https://www.devhandbook.com/javascript/dom/event-target/)


**To learn more about event types, visit:**
[Form Submission](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event)
[Mouseover Event](https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseover_event)
[Keydown](https://developer.mozilla.org/en-US/docs/Web/API/Element/keydown_event)
[Change Event](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event)
[Keyup](https://developer.mozilla.org/en-US/docs/Web/API/Element/keyup_event)

**References:**
[Finding HTML Elements](https://www.w3schools.com/js/js_htmldom_elements.asp)
[querySelector Method](https://www.w3schools.com/jsref/met_document_queryselector.asp)
[JavaScript Events](https://www.w3schools.com/js/js_events.asp)