0
votes

Is it possible to create a for loop which will go through the loop and assign a particular code to different css classes?

My css classes are defined in template.css file (there are 100 of classes with similar name), so obviuosly it should look something like the code below, which btw does nothin'?

for(i=1;i<101;i++) {
    $(document).ready(function () {  
        $('.inner' + i).hide(); 
        $('.outside' + i).hover(
            function () {
                $('.inner' + i, this).stop(true, true).slideDown(200);
            },
            function () {
                $('.inner' + i, this).stop(true, true).slideUp(200);            
            });
    });
}

And my classe are btw: outsude1, outside2, outside3... inner1, inner2, inner3...

1
The code above is not working, I tested it. I know about the classes it is cleaner.mpavlovic89

1 Answers

4
votes

Yes, it's possible, however your code will fail due to a very common pitfall in JavaScript: Each iteration of your loop create a series of functions, and each of these functions close over the same variable i. Later, when the functions execute, they will all have the same value for their single, shared instance of i, which will be 100.

You need to pass in a unique instance of i to each of your inner functions, and you can do this most easily with an immediately-invoked function expression, or IIFE.

$(function () { // this is the same as $(document).ready

  for (var i = 0; i < 100; ++i) {
    (function (i) {
        $('.inner' + i).hide(); 
        $('.outside' + i).hover(
            function () {
                $('.inner' + i, this).stop(true, true).slideDown(200);
            },
            function () {
                $('.inner' + i, this).stop(true, true).slideUp(200);            
            });
     }(i));
  }

});

Note that I've moved the $(document).ready outside of your for loop; this is an incidental optimization, not directly related to the solution, but definitely worthwhile. There is no point in binding 100 callbacks to $(document).ready, which your code does, when you can simply move the entire loop into a single callback.