[go: up one dir, main page]

DEV Community

Cover image for JavaScript Events: Simplified
ArmandeepKaur
ArmandeepKaur

Posted on

JavaScript Events: Simplified

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>
Enter fullscreen mode Exit fullscreen mode
//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")
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode
//used document.getElementByClassName, inserted the className into the parenthesis, and assigned the element to a variables called buttonByClass
const buttonByClass = document.getElementsByClassName("btn")
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode
//used document.getElementsByTagName(), passed the Tag Name surrounded by quotation marks, and assigned to a variable called buttonByTag
const buttonByTag = document.getElementsByTagName("button")
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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.

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()
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode
//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")
}
Enter fullscreen mode Exit fullscreen mode

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

    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>
Enter fullscreen mode Exit fullscreen mode
//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")
}
Enter fullscreen mode Exit fullscreen mode

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
event.target JavaScript

To learn more about event types, visit:
Form Submission
Mouseover Event
Keydown
Change Event
Keyup

References:
Finding HTML Elements
querySelector Method
JavaScript Events

Top comments (0)