hhh3112
hhh3112

Reputation: 2187

Jquery mouseenter question

I am a beginner with jquery. I have n divs which if i hover above them another div will fadein. Like this:

    $(".res2").mouseenter(function () {
        $("#jucInfores2").fadeIn("normal");
    });
    $(".res3").mouseenter(function () {
        $("#jucInfores3").fadeIn("normal");
    });
    $(".res4").mouseenter(function () {
        $("#jucInfores4").fadeIn("normal");
    });
    $(".res5").mouseenter(function () {
        $("#jucInfores5").fadeIn("normal");
    });
    $(".res6").mouseenter(function () {
        $("#jucInfores6").fadeIn("normal");
    });
    $(".res7").mouseenter(function () {
        $("#jucInfores7").fadeIn("normal");
    });
    $(".scl").mouseenter(function () {
        $("#jucInfoscl").fadeIn("normal");
    });
    $(".scc").mouseenter(function () {
        $("#jucInfoscc").fadeIn("normal");
    });
    $(".scr").mouseenter(function () {
        $("#jucInfoscr").fadeIn("normal");
    });
    $(".ml").mouseenter(function () {
        $("#jucInfoml").fadeIn("normal");
    });
    $(".mcl").mouseenter(function () {
        $("#jucInfomcl").fadeIn("normal");
    });

Is there another way to do this for me not to repeat so many times the code? If i have 20 such divs for example?

Upvotes: 1

Views: 149

Answers (2)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262919

I'd suggest you invert the logic and match the #jucInfo elements instead, then use the variable part of their ids to build the class selectors:

$("[id^='jucInfo']").each(function() {
    var $info = $(this);
    $("." + this.id.substr(7)).mouseenter(function() {
        $info.fadeIn("normal");
    });
});

Upvotes: 3

Dave Everitt
Dave Everitt

Reputation: 17846

One way is to wrap the main code in a Javascript function (very literal example for readability):

function jucInfo(res, infores) {
    $(res).mouseenter(function () {
        $(infores).fadeIn("normal");
    });
}

to which you can pass all your variables when you call the function:

jucInfo(".res2", "#jucInfores2");
jucInfo(".res3", "#jucInfores3");
...

To refine this further, place all your selector classes and ID pairs in a hash, then make a loop that repeats the above the required number of times (i.e. the number of elements in the hash).

Upvotes: 1

Related Questions