I'm trying to figure out how to optimise this code below. I tried to use iteration [i++]
, .each()
and .map()
.
$(document).ready(function(){
var formFilled = ['#div1','#div2'],
barFill = ['.bar1','bar2'],
progFill = ['#prog1','#prog2'];
$(formFilled[0]).on('click',function(){
$(progFill[0]).addClass('filled');
$(barFill[0]).addClass('filled');
})
$(formFilled[1]).on('click',function(){
$(progFill[1]).addClass('filled');
$(barFill[1]).addClass('filled');
})
});
The goal is that when i click on #div1
, it adds the class filled
to both .bar1
and #prog1
.
I was thinking of something along the lines of:
for(var i = 0; i < 2; i++) {
$(formFilled[i]).on('click',function(){
$(barFill[i]).addClass('filled');
$(progFill[i]).addClass('filled');
});
}
Sadly, this doesn't seem to work.
UPDATE
The solution from @Mike_C was exactly what I was looking for. This works very well:
var funcs = [];
function progClick(i) {
$(formFilled[i]).on('click',function(){
$(barFill[i]).addClass('filled');
$(progFill[i]).addClass('filled');
});
}
for (var i = 0; i < 2; i++) {
funcs[i] = progClick(i);
}