alinawab
alinawab

Reputation: 1

text not displaying in d3.append

trying to show a tooltip on a rect in d3js, it renders but text does now show.

from researching other issues I learned that I could not append 'text' to 'rect'

added a 'g' for both rect & then text element adds on mouseover, but still not displayed. also fixed earlier issue (thanks Alan) with 'g' going to nowhere but still issue with text not displaying.

const rects = svg.selectAll('g')
      .data(dataset); 

  rects.enter()
      .append('g')
      .on("mouseover", function() {
        d3.select(this)
        .transition()
        .duration(100)
        .attr("opacity", 0.9)
        .append('text')
        .attr("fill","black")
        .attr('x', 0)
        .attr('y',100)
        .text('Hello')
        }) 
      .append('rect')
      .attr('x', 0)
      .attr('width', 0)
      .attr('height', height)
      .attr('fill', function(d, i) {
        return z(i)
      })         
    .merge(rects)
      .transition()
      .duration(300)
        .attr('x', d => x(d.y0))
        .attr('width', d => x(d.y));

Upvotes: 0

Views: 641

Answers (2)

alinawab
alinawab

Reputation: 1

solved!

text was being drawn outside svg boundaries. the below code works to show a text below the rectangles

      const rects = svg.selectAll('g')
      .data(dataset); 

  rects.enter()
      .append('g')  
      .append('rect')
      .attr('x', 0)
      .attr('width', 0)
      .attr('height', height-150)
      .attr('fill', function(d, i) {
        return z(i)
      })
       .on("mouseover", function() {
        d3.select(this)
        .transition()
        .duration(100)
        .attr("opacity", 0.9);
        d3.select('g')
        .append('text')
        .attr("fill","black")
        .attr('x', 15)
        .attr('y',height - 130)
        .text('Hello')
        })
        .on("mouseleave", function() {
        d3.select(this)
        .transition()
        .duration(300)
        .attr("opacity", 1)
        svg.selectAll('text').remove();
        console.log("in mouse exit"); 
        })          
    .merge(rects)
      .transition()
      .duration(300)
        .attr('x', d => x(d.y0))
        .attr('width', d => x(d.y));

Upvotes: 0

Alan Grosz
Alan Grosz

Reputation: 1315

You are appending a text into a g to nowhere, because the d3.select('g') is not appending to your g. So, what you should to do is set the mouseover into the first append('g'), then in the callback, append to this. Something like this:

rects.enter()
      .append('g')
      .on("mouseover", function() {
        d3.select(this)
        .transition()
        .duration(100)
        .attr("opacity", 0.9)
        .append('text')
        .attr("fill","black")
        .attr('x', 0)
        .attr('y',100)
        .text('Hello')
      })
      .append('rect')
      .attr('x', 0)
      .attr('width', 0)
      .attr('height', height)
      .attr('fill', function(d, i) {
        return z(i)
      })
     ;

Upvotes: 1

Related Questions