Zade
Zade

Reputation: 692

Bind array of classes using jQuery

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');
        }
      }
    );
}

Upvotes: 0

Views: 366

Answers (2)

Rob W
Rob W

Reputation: 349142

Don't add pg[i] to the string, because it won't be interpreted as JavaScript variables. Instead, use this:

var pg = ["h", "e", "o"]
for(var i=0; i<pg.length; i++){
    (function(current){
        $("#nav li a."+current).mouseover(
            function () {
                if($(".content."+current).is(":hidden")) {
                    $(".content."+current).fadeIn('fast');
                }
            }
        );
    })(pg[i])
}

Upvotes: 2

David Hellsing
David Hellsing

Reputation: 108500

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 :hidden in the selector:

$.each(["h","e","o"], function(i, id) {
    $("#nav li a."+id).mouseover(function() {
        $(".content."+id+":hidden").fadeIn('fast');
    });
});

Upvotes: 3

Related Questions