listen in javascript

One way to listen for events in JavaScript is by using the addEventListener method. This method allows you to add an event listener to an element in the HTML DOM, such as a button. Here is an example of how to add a click event listener to a button:

index.tsx
const button = document.querySelector('#myButton');

button.addEventListener('click', function() {
  console.log('Button was clicked!');
});
141 chars
6 lines

In this example, we are selecting the button element with an ID of myButton using the querySelector method. We then add an event listener for the click event using the addEventListener method. The second argument to addEventListener is a callback function that will be executed when the event occurs. In this case, the callback function simply writes a message to the console.

By using event listeners, you can create interactive web pages that respond to user actions.

gistlibby LogSnag