0

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);
}
  • 2
    Your solution is the right idea, you're just going to run into a well-known problem. This should solve it: [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/q/750486/371184) – Mike Cluck Apr 05 '17 at 13:53
  • Why not just use a data attribute to target the proper bar. Or remove "#div" from $(this).attr('id'), and then append that to .bar + # – Andrew Ice Apr 05 '17 at 13:56

0 Answers0