how to listen for button clicks in javascript

To listen for button clicks in JavaScript, you can use the addEventListener method. This method takes two parameters: the name of the event to listen for (click in this case), and the function to execute when the event is triggered. You can select the button element by its ID, class, tag name or any other supported selectors.

Here's an example code:

// select the button element
const button = document.querySelector('#myButton');

// define the function to execute when the button is clicked
function buttonClicked() {
  console.log('Button was clicked!');
}

// add event listener to the button
button.addEventListener('click', buttonClicked);
296 chars
11 lines

In this example, we're selecting the button element with an ID of myButton, defining a function buttonClicked that logs a message to the console, and then adding an event listener using addEventListener. When the button is clicked, the buttonClicked function will be executed.

gistlibby LogSnag