relative(?) links:
http://api.jquery.com/jQuery.each/
hello
i got this navigation menu
<table>
<tr>
<td><div id="menuItem1" class="menuItem"><a href="http://www.w3schools.com">PORTFOLIO</a></div></td>
<td><div id="menuItem2" class="menuItem">ABOUT ME</div></td>
<td><div id="menuItem3" class="menuItem">CONTACT</div></td>
</tr>
<tr>
<td><div id="selectA1" class="selectA current"></div></td>
<td><div id="selectA2" class="selectA"></div></td>
<td><div id="selectA3" class="selectA"></div></td>
</tr>
</table>
the selectA class is a rectangle that will select the menuItem when your mouse moves over it
the long code would be like
$("#menuItem1").mouseover(function () {
$("#selectA1").stop().animate({opacity: 1},{ queue: false, duration: 200 });
});
$("#menuItem2").mouseover(function () {
$("#selectA2").stop().animate({opacity: 1},{ queue: false, duration: 200 });
});
$("#menuItem3").mouseover(function () {
$("#selectA3").stop().animate({opacity: 1},{ queue: false, duration: 200 });
});
$("#menuItem1").mouseout(function () {
$("#selectA1").stop().animate({opacity: 0},{ queue: false, duration: 400 });
});
$("#menuItem2").mouseout(function () {
$("#selectA2").stop().animate({opacity: 0},{ queue: false, duration: 400 });
});
$("#menuItem3").mouseout(function () {
$("#selectA3").stop().animate({opacity: 0},{ queue: false, duration: 400 });
});
but i thought it could be shorter if i’d loop over those
so i tried to loop through those menuItems so that the rectangle will appear for all menu items
what i tried in javascript, all didnt work
var i=1;
for (i=1;i<=3;i++) {
$("#menuItem"+i).mouseover(function () {
$("#selectA"+i).stop().animate({opacity: 1},{ queue: false, duration: 200 });
});
}
and
var i=1;
while (i<=3) {
$("#menuItem"+i).mouseover(function () {
$("#selectA"+i).stop().animate({opacity: 1},{ queue: false, duration: 200 });
});
and
$(".selectA").each(function (i) {
$("#menuItem"+i).mouseover(function () {
$("#selectA"+i).stop().animate({opacity: 1},{ queue: false, duration: 200 });
});
}
i++;
}
thank you for your help
First of all, you would be better off with
hoverrather than amouseover/mouseoutpair.Secondly, you don’t need to use
eachat all, there is a nice simple relationship between your.menuItemand.selectAelements: they have the same suffix number in theiridattributes. So, you could do the whole thing with something simple like this:Demo: http://jsfiddle.net/ambiguous/eza8b/
As far as why this:
doesn’t work goes, you’re having a classic closure problem. The functions that you supply to
.mouseoverare closures overiso all of them end up using the last value thatihad and that value is 4; that means that all of the inner selectors end up as$('selectA4')and that doesn’t refer to anything useful. If you really want to use a loop then you can forceito be evaluated when you want it to be with this:or this: