How to use addEventListener() In Javascript
The addEventListener() is an inbuilt function in JavaScript which takes the event to listen for, and a second argument to be called whenever the described event gets fired.
Example: In this example, we will see the use of addEventListener() for tracking a button click:
HTML
<!DOCTYPE html> < html > < body style = "text-align: center;" > < h1 style = "color: green;" > w3wiki </ h1 > < h4 > How to count the number of times a button is clicked? </ h4 > < button id = "btn" >Click Here!</ button > < p > Button Clicked < span id = "display" >0</ span > Times </ p > < script type = "text/javascript" > let count = 0; let btn = document.getElementById("btn"); let disp = document.getElementById("display"); btn.addEventListener("click", function () { count++; disp.innerHTML = count; }); </ script > </ body > </ html > |
Output:
How to count the number of times a button is clicked using JavaScript ?
At times, it becomes necessary to monitor the number of times a user clicks a button. In this article, we are going to learn how to count the number of times a button is clicked using JavaScript
Below are the approaches to count the number of times a button is clicked using JavaScript
Table of Content
- Using the onClick()
- Using addEventListener()
- Using a Closure