What am doing is attaching event on a class using a loop and index values are being used in the event handler code. Here is my code:
var classElements=document.getElementsByClassName("a");
for(var i=0; i<4; i++)
{
classElements[i].onClick=function(){
alert("Clicked button : "+i);
}
}
Whenever I click any of the buttons, it alerts:
Clicked Button : 4
What could be the problem?
JavaScript closes over the object and evaluates it later when it is called. At the time it is called, i is 4.
I think you want something like:
var classElements=document.getElementsByClassName("a");
for(var i=0; i<4; i++)
{
classElements[i].onClick=function(j) {
return function(){
alert("Clicked button : "+j);
};
}(i);
}
EDIT: shown with named functions to make the code more clear
var classElements=document.getElementsByClassName("a");
for(var i=0; i<4; i++)
{
var makeFn = function(j) {
return function(){
alert("Clicked button : "+j);
};
};
classElements[i].onClick = makeFn(i);
}
You need a closure in order to capture the changes of i. As Lou stated this is due to post evaluation.
var classElements=document.getElementsByClassName("a");
for(var i=0; i<4; i++)
classElements[i].onclick = (function(i){
return function(){ alert("Clicked button : " + i) };
})(i);
Related
Im injecting some number of buttons in my DOM using a for loop
function injectBtn () {
var output = '';
for(var i = 0 ; i < someNumber ; i++){
output += `<button id="button${i}">`;
}
document.getElementById('list').innerHTML = output;
}
Further I want to add event listeners to them like this, but nothing happens when I click them.
function addEvents () {
for (var i=0 ; i < someNumber ; i++) {
var btn = document.getElementById(`button${i}`);
btn.addEventListener('click', function () {
console.log('click');
}
}
}
I checked in my console, and I'm sure the buttons have been added to the DOM. What am i doing wrong?
So I understand why clicking on any button would pop up "Button [last value of i in loop] but why does i == 5 and not 4?
function myFn() {
var elems = document.getElementsByTagName('button');
var len = elems.length;
for (var i = 0; i < len; i++) {
elems[i].onclick = function() {
alert ("Button " + i);
};
}
alert ("Button " + i);
}
myFn();
http://jsfiddle.net/ka_tee_jean/fCtC8/
The last value of i variable is 5 at the end of the loop. So the alert statement inside myFn() will say "Button 5" on page load. The alert statements inside functions inside the for loop refer to the same variable via closure scope. Hence the clicks on the buttons also alert "Button 5".
Hope it helps! See below function which prints what you want. The caveat is introducing another closure scope by duplicating the value (pass-by-value mechanism in JavaScript) of i so that the onclick functions refer to another variable (i) which has a copy of the value.
function myFn() {
var elems = document.getElementsByTagName('button');
var len = elems.length;
for (var i = 0; i < len; i++) {
(function(i) {
elems[i].onclick = function() {
alert ("Button " + i);
};
})(i);
}
alert ("Button " + i);
}
myFn();
You have to change the function like:
js
function myFn() {
var elems = document.getElementsByTagName('button');
var len = elems.length;
for (var i = 0; i < len; i++) {
elems[i].onclick = function() {
alert (this.innerHTML);
};
}
alert ("Button " + i);
}
myFn();
As #Hunter McMillen mention i==5 is the condition that stops the loop.
Here is a fiddle
I have the following code that is in need of a closure:
var numItems = document.getElementsByClassName('l').length;
for (var i = 0; i < numItems; i++) {
document.getElementsByClassName('l')[i].onclick = function (e){
preview(this.href, i);
};
}
What happens is that whenever an item is clicked, preview always the same number for i
I suspect what I need to do is
function indexClosure(i) {
return function(e) {
preview(this.href, i);
}
}
And assign the onclick's like this:
document.getElementsByClassName('l')[i].onclick = indexClosure(i);
But then this would no longer refer to my link... how is this problem solved?
Use closure to capture the counter of the cycle:
var numItems = document.getElementsByClassName('l').length;
for (var i = 0; i < numItems; i++) {
(function(i){
document.getElementsByClassName('l')[i].onclick = function (e){
preview(this.href, i);
};
}(i))
}
doesn't onclick pass in (sender, eventArgs) allowing you to access this through sender?
I am looping through a list of links. I can correctly get the title attribute, and want it displayed onclick. When the page is loaded and when I click on a link, all of the link titles are alerted one by one. What am I doing wrong?
function prepareShowElement () {
var nav = document.getElementById('nav');
var links = nav.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].onclick = alert(links[i].title);
}
}
What you were doing was actually running the alert function.
enclosing the whole thing in an anonymous function will only run it when it is clicked
for (var i = 0; i < links.length; i++) {
links[i].onclick = function () {
alert(this.title);
}
}
You are assigning the onclick to the return value of alert(links[i].title); which doesn't make any sense, since onclick is supposed to be a function.
What you want instead is somethig like onclick = function(){ alert('Hi'); };
But
Since you are using a variable i in that loop you need to create a local copy of it
onclick = function(){ alert(links[i].title); }; would just use the outer scope i and all your links would alert the same message.
To fix this you need to write a function that localizes i and returns a new function specific to each link's own onclick:
onclick = (function(i){ return function(e){ alert(links[i].title); }; })(i);
Final result:
function prepareShowElement () {
var nav = document.getElementById('nav');
var links = nav.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].onclick = (function(i){ return function(e){ alert(links[i].title); }; })(i);
}
}
You can use jquery. To display title of the link on click.
$("#nav a").click(function() {
var title = $(this).attr('title');
alert(title);
});
links.forEach(function(link) {
link.onclick = function(event) {
alert(link.title);
};
}
Also note that your original solution suffered from this problem:
JavaScript closure inside loops – simple practical example
By passing in our iteration variable into a closure, we get to keep it. If we wrote the above using a for-loop, it would look like this:
// machinery needed to get the same effect as above
for (var i = 0; i < links.length; i++) {
(function(link){
link.onclick = function(event) {
alert(link.title);
}
})(links[i])
}
or
// machinery needed to get the same effect as above (version 2)
for (var i = 0; i < links.length; i++) {
(function(i){
links[i].onclick = function(event) {
alert(links[i].title);
}
})(i)
}
You need change .onclick for a eventlistener same:
function prepareShowElement () {
var nav = document.getElementById('nav');
var links = nav.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click',function() {
alert(links[i].title);
},false);
}
}
How does JavaScript closure work in this case and to be more specific: what does the (i) at the end do?
for(var i = 0; i < 10; i++) {
(function(e) {
setTimeout(function() {
console.log(e);
}, 1000);
})(i);
}
Also I'm trying to implement it in my code, and it seems I don't get it right
for (var i=0; i < len; i++) {
var formID = document.forms["form-" + i];
$(formID).bind("submit", validate);
$(formID).bind("change", function(i){
var divI = '#ind-' + i;
$(divI).css("background-color","green");
})(i);
}
This is a pattern used to create local scope around a variable. If this wasn't used then every call to console.log(i) would log the value of i (10) after the for loop finished.
for(var i = 0; i < 10; i++) {
// create new function
(function(e) {
// log each counter after 1 second.
setTimeout(function() {
console.log(e);
}, 1000);
// execute it with the counter
})(i);
}
The above is the same as this.
function foobar(e) {
setTimeout(function() {
console.log(e);
}, 1000);
}
for (var i = 0; i < 10; i++) {
(
foobar
)(i);
}
The real problem here is creating functions in a loop. don't do it :)
Your code
for (var i=0; i < len; i++) {
var formID = document.forms["form-" + i];
$(formID).bind("submit", validate);
// create a full closure around the block of code
(function() {
$(formID).bind("change", function(i){
var divI = '#ind-' + i;
$(divI).css("background-color","green");
})//(i); Don't call (i) here because your just trying to execute the
// jQuery element as a function. You can't do this, you need to wrap
// an entire function around it.
})(i);
}
But that is wrong, you want to delegate this job to something else.
function makeGreen(form, i) {
$(form).change(function() {
$("#ind-"+i).css("background-color", "green");
});
}
for (var i=0; i < len; i++) {
var formID = document.forms["form-" + i];
$(formID).bind("submit", validate);
// call a helper function which binds the change handler to the correct i
makeGreen(formID, i);
}
If you want to get a bit clever you can get rid of these anonymous functions
function makeGreen() {
var divId = $(this).data("div-id");
$(divId).css("background-color", "green");
}
for (var i=0; i < len; i++) {
$(document.forms["form-" + i])
.bind("submit", validate)
// store i on the form element
.data("div-id", "#ind-" + i)
// use a single event handler that gets the divId out of the form.
.change(makeGreen);
}
Edit
( // contain the function we create.
function(parameterA) {
window.alert(parameterA);
}
) // this now points to a function
("alertMessage"); // call it as a function.
Is the same as
( // contain the window.alert function
window.alert
) // it now points to a function
("alertMessage"); // call it as a function
Although not a direct answer to the closure question, here is my take on the issue.
I would re-write the logic to avoid the need for a closure (as it seems overcomplicated for the requirements)
The fact that there is a pattern in the naming of the forms makes things really easy
$('form[id^="form-"]').submit(validate)
.change(function(){
var divI = '#ind-' + this.id.replace('form-','');
$(divI).css("background-color","green");
});
demo http://jsfiddle.net/gaby/q8WxV/