unsureNovie77 unsureNovie77 - 1 year ago 86
CSS Question

Opacity update on all d3.svg.circles except for the class hovered

Completely stuck on this problem.
The goal is to be able to highlight certain data points on a scatterplot (based on cluster) when the user hovers onto that class of data. I have simplified the problem into the code below. Two clusters of data.

Here is my JS code:

var svg = d3.selectAll("body").append("svg").attr("width",500).attr("height",500);


Here is my CSS code:

svg:hover circle {
opacity: 0.5;
svg:hover #circle1:hover ~ #circle2 {
opacity: 1;
svg:hover #circle2:hover ~ #circle1 {
opacity: 1;

The first two CSS components work but hovering on circle2's does not change the opacity of circle1's.

Answer Source

First Problem: IDs are unique. Right now, you're repeating some IDs. Judging by your question's title, I changed them to class.

This is an easy method to change the opacity based on the class. First, you get the class of the hovered element:

var thisClass = d3.select(this).attr("class");

Then, you set the opacity according to the class. Here is a snippet:

var svg = d3.selectAll("body").append("svg").attr("width",500).attr("height",500);


d3.selectAll("circle").on("mouseover", function(){
  var thisClass = d3.select(this).attr("class");
  d3.selectAll("circle").attr("opacity", 0.5)
  d3.selectAll("." + thisClass).attr("opacity", 1)
}).on("mouseout", function(){
d3.selectAll("circle").attr("opacity", 1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download