1

I am trying to loop a function a number of times but it doesn't work for some reason. anybody see the problem?

this works

 <script>
 $(document).ready(function() {     
    $('.menuitem0').hover(function(){     
        $('.boxitem0').addClass('box_hover');  

    },     
    function(){    
        $('.box_item0').removeClass('box_hover');     
    });
}});  
</script>

but when i try and loop it it doesnt work

 <script>
 $(document).ready(function() {     
 for(var i = 0; i < 10; i++) {
    $('.menuitem'+i).hover(function(){     
        $('.box_item'+i).addClass('box_hover');  

    },     
    function(){    
        $('.box_item'+i).removeClass('box_hover');     
    });
}});  
</script>
sam
  • 345
  • 3
  • 12

1 Answers1

2

By the time the hover callback executes, the loop has finished, and i is always 10

You need a closure

$(document).ready(function() {     
 for(var i = 0; i < 10; i++) {
    (function(k) {
        $('.menuitem'+k).hover(function(){     
            $('.box_item'+k).addClass('box_hover');  

        },     
        function(){    
            $('.box_item'+k).removeClass('box_hover');     
        });
    }
}}); 

A better approach would be to target the correct elements, and not use a loop at all, for instance with the attribute starts with selector, and assuming the box is inside the menu

$(document).ready(function() {     
    $('[class^="menuitem"]').hover(function(){     
        $('.box_item', this).addClass('box_hover');  
    },     
    function(){    
        $('.box_item', this).removeClass('box_hover');     
    });
});   
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • thanks for your help but i'm still confused as to what to do. Here is a fiddle to show what I want to do http://jsfiddle.net/y6cCf/ – sam Mar 18 '14 at 10:03