DEV Community

Jennifer Tieu
Jennifer Tieu

Posted on

Self-Taught Developer Journal, Day 40: TOP DOM Manipulations and Events cont.

Today I learned...

Event Listeners

In the addEventListener() function, the function is called whenever the specified event occurs on the target. The target being a HTML element, Document object, etc.

 // target element to listen for event
 const elem = document.querySelector("#idExample");

 elem.addEventListener('click', (event) => {
   console.log(event.target.value);
   // `event` is passed into the callback from the 
   `.addEventListener` function when it receives a 'click' 
 event.
 });
Enter fullscreen mode Exit fullscreen mode

The arrow function argument in the addEventListener() second parameter is a callback. A callback is when a function is passed into another function as an argument.

The event object passed by the addEventListener() function into the callback represents the event itself.

The event listener can be applied on a group of nodes using the querySelectorAll().

Practice

  1. Grab the first exercise in Wes Bos’s JavaScript30 program by cloning the repo at https://github.com/wesbos/JavaScript30. Code along with the Video Tutorial to build the rest of the exercise.
  2. Watch the Event Capture, Propagation and Bubbling video from Wes Bos’s JavaScript30 program. If you want to code along with the video, you can use the contents of folder #25 from the repo you cloned above.

Resources

The Odin Project
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
https://briggs.dev/blog/understanding-callbacks

Discussion (1)

Collapse
369gtech profile image
Steven Mcleod

I will try this.