When an event occurs in the DOM, we can register event handlers for that event in Javascript. A callback is provided as the second argument to handle the event. It gets executed when that specific event fires in the DOM. Events includes click, keyup, keydown, mousedown, mouseenter, drag, resize and etc.
Handling click event in the DOM
Find the element using methods like querySelector.
const element = document.querySelector('.box');
Define the callback that will be executed when the event fires and pass it as the second argument of the event listener. An event object gets passed into the callback.
let callback = (ev) => {
console.log(ev);
}
Attach event listener to the element.
element.addEventListener('click', callback);
Alternatively, callbacks can also be passed as anonymous functions.
element.addEventListener('click', (ev) => {
console.log(ev);
});
Events like resize
and scroll
should be used carefully with debounce or throttle to improve the performance of the website or app.