sorry this may be a simple question. I am trying to build my first navigation using jQuery. The idea is that on hover of the button that the background colour and text colour changes as long as it is not the ‘selected’ button. I have all this working fine apart from the text colour. As in the jQuery it cannot see my loop variable:
function testIndex(navIndex){
for(i=0; i<=4; i++){
if(i != navIndex){
$('#nav a:eq('+i+')').hover(function(){
$(this).fadeTo('fast', 0.3, function(){
$(this).css('background-color','#ff3520');
$('#nav li:eq('+i+')').css('color', '#ffffff');
}).fadeTo('fast', 1);
},
function(){
$(this).fadeTo('fast', 0.3, function(){
$(this).css('background-color', '#e8e8e8');
$('#nav li:eq('+i+')').css('color', '#ff3520');
}).fadeTo('fast', 1);
});
};
};
};
On the
$('#nav li:eq('+i+')').css('color', '#ff3520');
The ‘i’ variable cannot be seen. I’ve tested it by inserting my own variables and it works.
Any advice?
Thanks.
Because you are in a loop, need a variable scope to keep reference to
iin the handler.In JavaScript calling a function makes a variable scope, so I used
$.eachfor the loop, because it calls the function for each array index.