w3resource

JavaScript button click event listener - Interactive program

JavaScript Event Handling: Exercise-1 with Solution

Write a JavaScript program that creates a button and add a click event listener to log a message when it's clicked.

Sample Solution:

JavaScript Code:

// Create a button element
const button = document.createElement('button');
button.textContent = 'Click me';

// Add click event listener to the button
button.addEventListener('click', () => {
  console.log('Button clicked!');
});

// Append the button to the document body
document.body.appendChild(button);

Output:

JavaScript button click event listener - Interactive program.
JavaScript button click event listener - Interactive program.

Note: Executed on JS Bin

Explanation:

First, we create a new button element using the "createElement()" method and set its text content to "Click me". We then add a click event listener to the button using the "addEventListener()" method. When the button is clicked, the callback function inside the event listener is executed, which logs the message "Button clicked!" to the console.

Finally, we append the button to the document body using the "appendChild()" method so that it becomes visible on the page.

Flowchart:

Flowchart: JavaScript button click event listener - Interactive program.

Live Demo:

See the Pen javascript-event-handling-exercise-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Event Handling Exercises Previous: JavaScript Event Handling Exercises Home.
Event Handling Exercises Next: JavaScript Dropdown menu - Interactive program.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/event/javascript-event-handling-exercise-1.php