...

jQuery for loop with hover function

hothousegraphix
01-21-2009, 03:22 AM
I'm trying to loop through my doc and alter the display of 5 containers on hover.

I can run my hover functions with no problem

$(document).ready(function() {

myDivs = '5';
$('li').hover(

function() {
$('#div_1').addClass("hover");
alert(myDivs);
},

function() {

$('#div_1').removeClass("hover");

}

);

});

I can establish my for loop with no problem

$(document).ready(function() {
myDivs = '5';
for(z=1;z<=myDivs;z++){
alert(z);
};
});

But when I attempt to combine - I get some odd behavior - I'm sure it's my syntax but I'm not sure exactly what it is.

$(document).ready(function() {
myDivs = '5';
for(z=1;z<=myDivs;z++){
alert('#div_'+ z); // here z increments
$('li').hover(
function() {
$('#div_'+ z).addClass("hover");
alert('#div_'+ z); // here z equal to 6 all the time ???
},
function() {
$('#div_'+ z).removeClass("hover");
}
);
}
});

any advice would be much appreciated.

Thanks

hothousegraphix
01-21-2009, 05:53 PM
not sure if I'm making progress but it looks like I need to declare a variable within the for loop to represent my counter; like

$(document).ready(function() {
myDivs = '5';
for(z=1;z<=myDivs;z++){
count = z; // new counter variable
alert('#div_'+ count); // variable increments
$('li').hover(
function() {
alert('#div_'+ count); // variable now equal to 5 for every iteration ???
$('#div_'+ count).addClass("hover");
},
function() {
$('#div_'+ count).removeClass("hover");
}
);
}
});

I'm still a bit lost as to why may variable is not increasing in value with "z".

bgallegos
01-23-2009, 03:03 PM
Can you post how your html is structured? Thanks

podpi
11-26-2009, 05:35 PM
Code:

Javascript:
for (k = 1; k <= 2; k++) {

readMoreStr = "#readMore" + k;

$(readMoreStr).click(function() {
alert("Read more id: " + readMoreStr);
// ALWAYS ALERTS "Read more id: 2" on both readmore divs when clicked
});
}

HTML:

<div class="readMore" id="readMore1">
<a href="" title="read more" class="readMoreLink">read more</a>
</div>
<div class="readMore" id="readMore2">
<a href="" title="read more" class="readMoreLink">read more</a>
</div>



any ideas guys?
thx



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum