Mark As Completed Discussion

Event Listener

In JavaScript, an event listener is a function that waits for a specific event to occur and then triggers a set of instructions or actions. Event listeners are used to respond to user interactions with a web page or application.

When an event occurs, such as a click on a button or a key being pressed, the event listener associated with that event is invoked. It allows you to define custom behavior for different events.

To attach an event listener to an element, you can use the addEventListener method. This method takes two arguments: the type of event to listen for and the function that should be executed when the event occurs.

Here's an example of adding a click event listener to a button:

JAVASCRIPT
1const button = document.getElementById('my-button');
2
3button.addEventListener('click', event => {
4  console.log('Button clicked!');
5});

In this example, when the button with the id my-button is clicked, the event listener function will be called. It will log the message 'Button clicked!' to the console.

Event listeners can be attached to various types of events, such as click, submit, keydown, mousemove, and more. They allow you to capture user interactions and perform actions based on those interactions. By using event listeners, you can create interactive and dynamic web pages.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment