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.
});
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
- 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.
- 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
Top comments (1)
I will try this.