1

I have this d3 project where I created bar chart. I have several bars and I want data to display once I hover over the specific bar. However, for some reason it doesn't display the content despite the data and css being present. I created rects elements as bars and and a div element with the class of tooltip that includes the data. Please help.

Here is my code:

  chart.selectAll("rect")
    .data(json.data)
    .enter()
    .append("rect")
    .attr("x", (d) => xScale(parseDate(formatDate(d[0]))))
    .attr("y", (d) => yScale(d[1]))
    .attr("height", (d) => height - yScale(d[1]))
    .attr("width", xScale.bandwidth())
    .attr("class", "rect-col")

    .append("div")
    .attr("class", "tooltip")
    .text((d) => d[0] + d[1])
    .on("mouseenter", function (d, i) {
      //d3.select(this).style("fill", "#EE9A2F");
      d3.select(this).style("visibility", "visible");


    })
    .on("mouseleave", function (d, i) {
      //d3.select(this).style("fill", "#EECF10");
      d3.select(this).style("visibility", "visible");
    });

my css:

.tooltip {           
  text-align: center;           
  width: 60px;                  
  height: 28px;                 
  padding: 2px;             
  font: 12px sans-serif;        
  background: green;   
  border: 0px;      
  border-radius: 8px;           
  pointer-events: none;    
  color: red;
  visibility: hidden;

}

link to my codepen codepen

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
Roger
  • 597
  • 9
  • 32

1 Answers1

1

Simply put: you cannot append a <div> into an SVG <rect>.

The solution here is creating a selection for the div...

const tooltip = d3.select("body")
    .append("div")
    .attr("class", "tooltip");

... and then, inside the "mouseenter" listener of the rectangles:

tooltip.style("visibility", "visible")
    .text(d[0] + d[1])

Here is your updated CodePen, you'll see the tooltip below the chart: https://codepen.io/anon/pen/LaZgvp?editors=0010. This, probably, will led to your next question: "how to position the tooltip over/next to the respective rectangle?" The answer to that question, certainly a duplicate, can be found with a simple search (for instance: https://stackoverflow.com/a/41625629/5768908 and https://stackoverflow.com/a/40720100/5768908).

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
  • Spot on. I didn't know you couldn't attach a div to rect. Thank you Gerardo and yes I was going to ask how to place it on the correct rectangle. Thank you again :) Have a great day. – Roger Mar 04 '19 at 11:58