Is it possible to simplify the following jQuery using a for loop?
$("#nav li a.h").mouseover(
function () {
if($(".content.h").is(":hidden")) {
$(".content.h").fadeIn('fast');
}
}
);
$("#nav li a.e").mouseover(
function () {
if($(".content.e").is(":hidden")) {
$(".content.e").fadeIn('fast');
}
}
);
$("#nav li a.o").mouseover(
function () {
if($(".content.o").is(":hidden")) {
$(".content.o").fadeIn('fast');
}
}
);
I tried this, but no luck:
var pg = ["h","e","o"];
for (var i = 0; i < pg.length; i++) {
$("#nav li a.pg[i]").mouseover(
function () {
if($(".content.pg[i]").is(":hidden")) {
$(".content.pg[i]").fadeIn('fast');
}
}
);
}
pg[i]inside quotes will not work as a variable, you need to append it to the selector string using+.More optimizations: The $.each method is fast and good to use when looping, and you don’t need to check if
elem.is(':hidden'), just include:hiddenin the selector: