How to use a Closure In Javascript
A closure is a feature of JavaScript that allows inner functions to access the outer scope of a function.
Example: In this example, we will see the use of closure for tracking the button count.
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 > function createCounter() { let count = 0; return function () { count++; return count; } } const counter = createCounter(); const button = document.getElementById("btn"); const disp = document.getElementById("display"); button.addEventListener("click", () => { disp.innerHTML = counter(); }); </ 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