Events and Event Listeners

Expert-Level Explanation

Events in the DOM are actions or occurrences that happen in the web browser, which the browser tells you about so you can respond to them in some way. Event listeners are used to listen for these events and execute a function when the event occurs, like click, mouseover, or keydown.

Creative Explanation

Events and event listeners are like doorbells in an apartment building. When a visitor presses a doorbell (an event like a click), the corresponding apartment is notified (event listener), and the resident can respond (execute a function).

Practical Explanation with Code

const button = document.querySelector('.button');
button.addEventListener('click', function() {
    console.log('Button was clicked!');
});

Real-world Example

Imagine a customer service desk. When a customer presses a service bell (event), the staff (event listener) responds by providing assistance (function is executed).