I am trying to select a list of divs (foo#) and fadeIn another div (zxcv#) on hover. I assigned a var in javascript but the end effect is only showing in foo6?
<div class="foo1"><div class="zxcv1"></div></div>
<div class="foo2"><div class="zxcv2"></div></div>
<div class="foo3"><div class="zxcv3"></div></div>
<div class="foo4"><div class="zxcv4"></div></div>
<div class="foo5"><div class="zxcv5"></div></div>
<div class="foo6"><div class="zxcv6"></div></div>
<script type="text/javascript">
for (var i = 1; i < 6; i++) {
$(".foo"+i).hover(
function ()
{
$(".zxcv"+i).fadeIn();
}, function ()
{
$(".zxcv"+i).fadeOut();
});
}
</script>
You could use an "attribute starts with" selector:
That removes the need for a loop, since most jQuery methods apply to every element in the set.
Try use :nth-child()
You can select all with
$("[class^='foo']")
(also see here):Also see my example.
You are closing over the loop variable
i
in your callbacks, which has the end result thati
is always6
inside them (you can check this out withconsole.log
oralert
).To solve the problem you need to make sure that each of your callbacks gets its own value of
i
. Since Javascript variables are not scoped to blocks but to whole functions, this means that you need to call a function with the current value ofi
each time:A couple of notes:
i < 6
instead ofi <= 6
-- is this a bug?