Reputation:
I'm trying to practice closures and scopes, with anonymous functions.
There are 4 HTML buttons, and on click, I want javascript to identify what button number they are, and how many times they've been clicked.
I am not sure if this is even properly setup.
Looking forward to your inputs and advice. Below are the code. Thanks in advance!!
var buttons = document.querySelectorAll("button");
buttons.forEach(function(button){
button.addEventListener("click", function(){
return (function(input){
var increment = 0;
return function(){
increment++;
alert("button " + input.textContent + ":" + " has been clicked " + increment + " times." );
}
})(button);
});
});
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
Upvotes: 2
Views: 73
Reputation: 1660
Of course anonymous functions can return other functions. Functions are first-class-citizens in js. Every embedded function has access on the context of the enveloping function, except for the this
property. You can use the context of the four forEach functions to store the number of increments. When you return something from withing an event listener, i dont know if this return is ever used somewhere. It maybe just exists the function.
var buttons = document.querySelectorAll("button");
buttons.forEach(function(button){
var increment = 0;
button.addEventListener("click", function(event){
increment++;
alert("button " + event.currentTarget.innerHTML + ":" + " has been clicked " + increment + " times." );
}
);
});
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
Upvotes: 1