Search code examples
jquerymultiple-instancesjquery-hover

Highlighting multiple elements on hover


Highlighting multiple elements on hover of one element is a common question. There are a few similar questions on Stack about this issue, but it typically only deals with one tier of information.

For example: When I click this box, I would like to highlight another box.

I am wanting to add this functionality to three tiers of information, and have it work interchangeably.

See the fiddle here.

You can see it is working, but I am wondering if there is a way to do it better. For instance, it is ok when I have about 12 options for each tier, but what if it was 50, or 100? Is there a way to streamline it, so it would be easier to add multiple items in each tier without manually adding every class name relative to the id?

It seems like I could open up the explicit class names a bit by passing a variable to a function, but I don't know how to get ALL of the class names of the hovered object, and check those against the class names in the other tiers.

Or, if you know of a plugin out there that does this magically?


Solution

  • That is about the best way to do it with jQuery. You can also do a similar effect with CSS and classes applied to parent elements.

    For instance:

    <div>
        <div class="bob">This is Bob.</div>
    </div>
    

    Then add a class to the parent element:

    <div class="show-bob">
        <div class="bob">This is Bob.</div>
    </div>
    

    Of course, the CSS is key here:

    .bob { opacity: 0.75 }
    .show-bob .bob { opacity: 1 }
    

    Sure, you need to add some CSS animation properties there for real feature parity, but you get the gist.