javascriptjquery

jQuery – How can I simplify this?


I'm very new to jquery and only have a very basic knowledge of how it works. This is basically what I have, and it works fine but I'm wondering if there's a way to simplify it because it seems awfully repetitive and bulky? I've tried doing this a number of different other ways, but I haven't been able to make any of them work.

$(".legend.a").on("mouseenter", function() {
    $(".box").not(".a").css({"opacity": "0.4"});
}); 
$(".legend.b").on("mouseenter", function() {
    $(".box").not(".b").css({"opacity": "0.4"});
}); 
$(".legend.c").on("mouseenter", function() {
    $(".box").not(".c").css({"opacity": "0.4"});
}); 
$(".legend").on("mouseleave", function() {
    $(".box").css({"opacity": "1.0"});

This is the html:

<div id="legend">
<div class="legend a">a</div>
<div class="legend b">b</div>
<div class="legend c">c</div>
</div>
<div id="box">
<div class="box a">a</div>
<div class="box b">b</div>
<div class="box c">c</div>
</div>

But, not only do I have classes a, b, and c, there's another 6 or 7 other classes as well. The classes .box .a, .box .b, etc. are used more than once, or I'd just use ids, and classes .a, .b, etc. are being used to give the corresponding .box and .legend divs the same background colour.

I feel like there must be a simpler way of doing this rather than using a lot of repetition. Any help with this would be greatly appreciated, thanks.


Solution

  • Use the class of legend for the selector

    $('.legend').on('mouseenter',function(){
        $('.box').not('.'+this.className.replace("legend","").trim()).css({'opacity':'0.4'});
    });
    $(".legend").on("mouseleave", function() {
        $(".box").css({"opacity": "1.0"});
    });
    

    DEMO