cant change the opacity of a specific path in D3js sunburst chart

210 Views Asked by At

My objective is to change the opacity of a specific path.

This is where I am adding a path for each slice in the chart:

h = f.selectAll("path").data(o);
h.enter().append("path")        
.attr("id", function (t, n) { return "path-" + n})
.attr("d", x).attr("fill-rule", "evenodd").style("fill", n).on("click", l)
.on("mouseover", function(t,n) {mouseover("path-" + n)});

inside of the mouseover function here is what I have tried:

function mouseover(d){ 
    // d is the id of the path that was hovered over
    // d looks like 'path-20'

    d3.selectAll("path").style("opacity", 0.3); // changes opacity for entire sunburst chart        
    d3.selectAll(d).style("opacity", 0.3); // does nothing
    d3.selectAll("path-20").style("opacity", 0.3); // does nothing
    d3.select(d).style("opacity", 0.3); // does nothing
    d3.select("path-20").style("opacity", 0.3); // does nothing
}
1

There are 1 best solutions below

0
On

Firstly, if you want to select by a class, use .<class-name> instead. If you want to select by an ID, use #<id>. These are universal selectors from CSS, jQuery, vanilla JavaScript, and also D3.

Much easier, though, is that for the function on("mouseover", function() { ... }), on the place of the dots, this now points to the HTMLElement you want to select.

That makes the following function perfect for what you want:

const data = d3.range(5);

d3.select('svg')
  .selectAll('rect')
  .data(data)
  .enter()
  .append('rect')
  .attr('width', 20)
  .attr('height', 20)
  .attr('x', function(d, i) {
    return 30 * i;
  })
  .attr('y', 40)
  .on('mouseover', function() {
    d3.select(this).attr('opacity', 0.2);
  })
  .on('mouseleave', function() {
    d3.select(this).attr('opacity', null);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>