D3: Tool Tip Does not Render Dynamically with Callback in Text Method

Does anyone know why

     .text((d) => d)

is working to render dynamically in

  svg.selectAll("text")

but not in

  svg.selectAll("title")

As of now, the tooltip only display the first element in the dataset.
How can I make the tooltip render dynamically? What do I miss?
Thank you.

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

<style>
.bar:hover {
  fill: brown;
}
</style>
<body>
<script>
  const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];

  const w = 500;
  const h = 100;

  const svg = d3.select("body")
                .append("svg")
                .attr("width", w)
                .attr("height", h);

  svg.selectAll("rect")
     .data(dataset)
     .enter()
     .append("rect")
     .attr("x", (d, i) => i * 30)
     .attr("y", (d, i) => h - 3 * d)
     .attr("width", 25)
     .attr("height", (d, i) => d * 3)
     .attr("fill", "navy")
     .attr("class", "bar")
     // Add your code below this line

  svg.selectAll("title")
     .data(dataset)
     .enter()
     .append("title")
     .text((d) => d)
     // Add your code above this line

  svg.selectAll("text")
     .data(dataset)
     .enter()
     .append("text")
     .text((d) => d)
     .attr("x", (d, i) => i * 30)
     .attr("y", (d, i) => h - (d * 3 + 3))

</script>
</body>
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36

Challenge: Add a Tooltip to a D3 Element

Link to the challenge:

This is the right way to do it:


<style>
.bar:hover {
  fill: brown;
}
</style>
<body>
<script>
  const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];

  const w = 500;
  const h = 100;

  const svg = d3.select("body")
                .append("svg")
                .attr("width", w)
                .attr("height", h);

  svg.selectAll("rect")
     .data(dataset)
     .enter()
     .append("rect")
     .attr("x", (d, i) => i * 30)
     .attr("y", (d, i) => h - 3 * d)
     .attr("width", 25)
     .attr("height", (d, i) => d * 3)
     .attr("fill", "navy")
     .attr("class", "bar")
     // Add your code below this line

  svg.selectAll("rect")
     .append("title")
     .text((d, i) => d)
     // Add your code above this line

  svg.selectAll("text")
     .data(dataset)
     .enter()
     .append("text")
     .text((d) => d)
     .attr("x", (d, i) => i * 30)
     .attr("y", (d, i) => h - (d * 3 + 3))

</script>
</body>

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.