Strategy 3: toggle css classes


In the previous lesson, we learned how to modify a hovered graph item using the :hover CSS pseudo-class.

However, this approach has design limitations. To achieve a more effective highlighting effect, it's better to simultaneously dim the other graph items.

This can be accomplished using CSS alone, with the help of the CSS descendant selector.

Wip
4 minutes read

Toggle class in JS

Problem above: when mouse enter the chart area, triggers effect even if no marker hovered over.

Solution: CSS compound class selecter (MDN doc)

In CSS, a compound class selector combines multiple class names to target elements that match all of the specified classes.

We can use the same css as the above example, but add the highlight class using javascript:

onMouseEnter={() => {
  if (ref.current) {
    ref.current.classList.add(styles.hasHighlight);
  }
}}
onMouseLeave={() => {
  if (ref.current) {
    ref.current.classList.remove(styles.hasHighlight);
  }
}}
Mark (90)Robert (12)Emily (34)Marion (53)Nicolas (58)

A donut chart with clean inline legends, built thanks to the centroid function of d3.js.

Pros & Cons

More examples

The examples below all use this strategy to implement their hover effect.