A function inside a for loop with jQuery and Javascript - javascript

i have the following code :
$(document).ready(function () {
for (i = 1; i <= number_of_banners; i++) {
var selector = "#link_" + i;
$(selector).click(function () {
alert(i);
});
}
});
but the alert() can't get the "i" variable from the for loop.
How can I use the i variable of for loop inside the .click function ?

you can use this code :
$(document).ready(function () {
for (var i = 1; i <= number_of_banners; i++) {
var selector = "#link_" + i;
$(selector).on('click', {id: i}, function (e) {
alert(e.data.id);
});
}
});
you should use on method and use click argument in it instead of using onclick method

Using jQuery .on(event, data, handler) you can do it easily.
$(document).ready(function () {
for (var i = 1; i <= number_of_banners; i++) {
var selector = "#link_" + i;
$(selector).on('click', {id: i}, function (e) {
alert(e.data.id);
});
}
});
Working sample

Might this happen be due the fact of the JavaScript hoisting JavaScript Scoping mechanism??
For instance:
example of wrong loop variable binding
doesn't work as JavaScript uses function scope rather than block scope as we're usually accustomed from other languages like Java and C#. In order to make it work, one has to create a new scope by explicitly creating a new anonymous function which then binds the according variable:
example of correct loop variable binding
I know this doesn't directly answer the question above, but might still be useful though for others stumbling over this question.

I think you can pass it as a parameter into the anonymous function as long as the function is declared within a scope that can access i.
function (i) {
alert(i);
}

a quick solution would be to use the eventData and store the current i in that:
$(document).ready(function () {
for (var i = 1; i <= number_of_banners; i++) {
var selector = "#link_" + i;
$(selector).bind('click', i, function (e) {
alert(e.data);
});
}
});
if you are using jquery 1.7+ then use on instead of bind

Related

addEventListener : how to limit a callback function?

Actually i want to give button a functionality such that it is clickable for certain times only, how can i do it?
also how can i pass a user defined input/parameter to callback function of addEventListener.
As Wai, You can use a global variable in JS, or if using a framework then store that variable in state and in the callback function verify if it's within the limit or otherwise increment and execute the function, below is a sample implementation.
const countsClicked = 0;
const button = document.getElementById('my-button');
button.addEventListener("click", function() {
if (countsClicked >= 5) {
return;
}
//execute
++countsClicked;
});
Here is how I did that
<script>
var count = 0;
document.getElementById("your_id").addEventListener("click", () => {
if (count < 10) {
count++;
console.log("Clicked");
}
});
</script>

jQuery - passing variable to event by data

I would like to create some objects dynamically and bind events to them (not important what events).
I'm passing a number to the event in order to distinguish those items. There is my code:
$('#add_btn').click(function() {
var cont = $('#buttons');
for(var i=0; i<5; i++) {
var new_btn = $('<input>').attr('type', 'button').val(i);
new_btn.click(function() {
alert(i);
});
cont.append(new_btn);
}
});
When I click on any from newly created buttons, displayed number is 5.
I think that i variable is passing by reference, but the question is: how to avoid passing variable by reference? More, even if I crate new variable before binding event (so the reference should point to another object, for example new_val = i.toString()), value is still same for all buttons (then its 4, understandable).
I know that I can attach new_btn.data() and read it in event, but I'm not sure if it won't be an overhead.
Link to jsfiddle: http://jsfiddle.net/Jner6/5/.
Since you are using a closure scoped variable in a loop, inside the loop you need to create a private closure.
$('#add_btn').click(function () {
var cont = $('#buttons');
for (var i = 0; i < 5; i++) {
(function (i) {
var new_btn = $('<input>').attr('type', 'button').val(i);
new_btn.click(function () {
alert(i);
});
cont.append(new_btn);
})(i)
}
});
Seems like you run into closures issue, try this:
(function( i ) {
new_btn.click(function() {
alert(i);
});
})( i );
This will create immediate invoked function that will closure your variable i so you can use it in future. For now you just overriding i variable in your for-loop so you will have always same value that will equal last for-loop iteration.
Don't make functions within a loop.
DEMO
var cont = $('#buttons');
$('#add_btn').click(function() {
for(var i=0; i<5; i++) {
$('<input>', {type:'button', value:i}).appendTo( cont );
}
});
cont.on('click', ':button', function() {
alert( this.value );
});

Defining anonymous functions in a loop including the looping variable?

I know that this code doesn't work and I also know why.
However, I do not know how to fix it:
JavaScript:
var $ = function(id) { return document.getElementById(id); };
document.addEventListener('DOMContentLoaded', function()
{
for(var i = 1; i <= 3; i++)
{
$('a' + i).addEventListener('click', function()
{
console.log(i);
});
}
});
HTML:
1
2
3
I want it to print the number of the link you clicked, not just "4".
I will prefer to avoid using the attributes of the node (id or content), but rather fix the loop.
Wrap the loop block in its own anonymous function:
document.addEventListener('DOMContentLoaded', function()
{
for(var i = 1; i <= 3; i++)
{
(function(i) {
$('a' + i).addEventListener('click', function() {
console.log(i);
})
})(i);
}
}
This creates a new instance of i that's local to the inner function on each invocation/iteration. Without this local copy, each function passed to addEventListener (on each iteration) closes over a reference to the same variable, whose value is equal to 4 by the time any of those callbacks execute.
The problem is that the inner function is creating a closure over i. This means, essentially, that the function isn't just remembering the value of i when you set the handler, but rather the variable i itself; it's keeping a live reference to i.
You have to break the closure by passing i to a function, since that will cause a copy of i to be made.
A common way to do this is with an anonymous function that gets immediately executed.
for(var i = 1; i <= 3; i++)
{
$('a' + i).addEventListener('click', (function(localI)
{
return function() { console.log(localI); };
})(i);
}
Since you're already using jQuery, I'll mention that jQuery provides a data function that can be used to simplify code like this:
for(var i = 1; i <= 3; i++)
{
$('a' + i).data("i", i).click(function()
{
console.log($(this).data("i"));
});
}
Here, instead of breaking the closure by passing i to an anonymous function, you're breaking it by passing i into jQuery's data function.
The closure captures a reference to the variable, not a copy, which is why they all result in the last value of the 'i'.
If you want to capture a copy then you will need to wrap it in yet another function.

Javascript Closure Problem

I know this kind of question gets asked alot, but I still haven't been able to find a way to make this work correctly.
The code:
function doStuff () {
for (var i = 0; i< elementsList.length; i++) {
elementsList[i].previousSibling.lastChild.addEventListener("click", function(){
toggle(elementsList[i])}, false);
}
} // ends function
function toggle (element) {
alert (element);
}
The problem is in passing variables to the toggle function. It works with the this keyword (but that sends a reference to the clicked item, which in this case is useless), but not with elementsList[i] which alerts as undefined in Firefox.
As I understood it, using anonymous functions to call a function is enough to deal with closure problems, so what have I missed?
Try:
function startOfFunction() {
for (var i = 0; i< elementsList.length; i++) {
elementsList[i].previousSibling.lastChild.addEventListener(
"click",
(function(el){return function(){toggle(el);};})(elementsList[i]),
false
);
}
} // ends function
function toggle (element) {
alert (element);
}
The Problem is, that you want to use the var i! i is available in the onClick Event, (since closure and stuff). Since you have a loop, i is counted up. Now, if you click on any of the elements, i will always be elementsList.length (since all event functions access the same i )!
using the solution of Matt will work.
As an explanation: the anonymous function you use in the for loop references the variable "i" to get the element to toggle. As anonymous functions use the "live" value of the variable, when somebody clicks the element, "i" will always be elementsList.length+1.
The code example from Matt solves this by sticking the i into another function in which it is "fixated". This always holds true:
If you iterate over elements attaching events, do not use simple anonymous functions as they screw up, but rather create a new function for each element. The more readable version of Matts answer would be:
function iterate () {
for (var i = 0; i < list.length; i++) {
// In here, i changes, so list[i] changes all the time, too. Pass it on!
list[i].addEventListener(createEventFunction(list[i]);
}
}
function createEventFunction (item) {
// In here, item is fixed as it is passed as a function parameter.
return function (event) {
alert(item);
};
}
Try:
function doStuff () {
for (var i = 0; i< elementsList.length; i++) {
(function(x) {
elementsList[x].previousSibling.lastChild.addEventListener("click", function(){
toggle(elementsList[x])}, false);
})(i);
}
} // ends function
I think it might be an issue with passing elementsList[i] around, so the above code has a closure which should help.

adding onfocus event handler to every element

I'm getting an undefined message on all of my handlers. I want to bind a handler to every element and want to output the value. What is wrong with this code? Thanks!
for (var i = 0; i < document.forms[0].elements.length; i++ ){
document.forms[0].elements[i].onfocus = test(this);
}
function test(ele){
alert(ele.value);
}
You need to assign a function. At the moment you are assigning the return value of test(window) which is undefined.
onfocus = test;
Then reference the element inside the function:
function test(){
alert(this.value);
}
You need to change both the assignment and the function, since the element will no longer be passed in as a parameter, like this:
for (var i = 0; i < document.forms[0].elements.length; i++ ){
document.forms[0].elements[i].onfocus = test;
}
function test(){
alert(this.value);
}
As an event handler, this inside test will refer to the element you're dealing with, so just get the value from that.
The alternative version of your current approach would be the same test method, but with an anonymous function wrapper to pass the element itself as a parameter:
for (var i = 0; i < document.forms[0].elements.length; i++ ){
ddocument.forms[0].elements[i].onfocus = function() { test(this); };
}
function test(ele){
alert(ele.value);
}
As both Nick and David pointed out, the way you assign the event handler is not correct. However, to achieve what you are trying (pass in a context) you can use a delegate function. Like this:
for (var i = 0; i < document.forms[0].elements.length; i++ ){
var ele = document.forms[0].elements[i];
ele.onfocus = delegate(ele, test);
}
function delegate(obj, handler) {
return function () {
handler.call(obj);
}
}
function test() {
alert(this.value);
}
What the delegate function does, is call your handler function setting the context of this. See the documentation for the Function object for further information. For even further reading, I recommend The this keyword and Introduction to events on Quirksmode.

Categories