0

I am trying to get text to display on mouseover of name on an x-axis. This stackoverflow post almost gets there, except that i am unable to pass data to the function called on mouseover.

// Add the X Axis
  svg.append("g")
    .attr("class", "axis")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x))
    .selectAll("text")
    .style("text-anchor", "end")
    .style("font", "7px times")
    .attr("dx", "-.8em")
    .attr("dy", ".15em")
    .attr("transform", "rotate(-65)")
    .on("mouseover", function(d) {
      return tooltip.style("visibility", "visible")
    })
    .on("mouseout", function(d) {
      return tooltip.style("visibility", "hidden");
    });

  var tooltip = d3.select("#info")
    .append("div")
    .style("position", "absolute")
    .style("z-index", "10")
    // .style("visibility", "hidden")
    .text("a simple tooltip" + d.name);

When I remove d.name it works. I am unable to pass d to tooltip.

Perhaps I need to use .data(data).enter() which i have tried but maybe I am not using it correctly.

Thanks,

https://d3js.org/d3.v4.min.js is the only library I am using.

Shane G
  • 3,129
  • 10
  • 43
  • 85

1 Answers1

2

Can you just set the text in the mouseover callback, where you have access to d?

// Add the X Axis
svg.append("g")
    .attr("class", "axis")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x))
    .selectAll("text")
    .style("text-anchor", "end")
    .style("font", "7px times")
    .attr("dx", "-.8em")
    .attr("dy", ".15em")
    .attr("transform", "rotate(-65)")
    .on("mouseover", function(d) {
        return tooltip
            .style("visibility", "visible")
            .text("a simple tooltip" + d.name);
    })
    .on("mouseout", function(d) {
        return tooltip.style("visibility", "hidden");
    });

var tooltip = d3.select("#info")
    .append("div")
    .style("position", "absolute")
    .style("z-index", "10")
    // .style("visibility", "hidden")
    // .text("a simple tooltip" + d.name);
user3432422
  • 1,359
  • 1
  • 11
  • 13
  • Ah, thought I'd tried that actually. It works. Thanks – Shane G Aug 02 '17 at 14:53
  • I was't using 'return tooltip...' – Shane G Aug 02 '17 at 14:58
  • But i still don't see why I can't pass 'd' in through the function. – Shane G Aug 02 '17 at 15:15
  • 1
    Through what function? The only function here is the mouseover handler right? The bit that creates the tooltip isn't a function, that code is run way before any mouseover handler is called, so there's no way for it to get access to the 'd' at that point. – user3432422 Aug 03 '17 at 06:43
  • I mean why can't 'd.name' in ' .text("a simple tooltip" + d.name);' be displayed? It's as if d is passed into the function(d) and that function returns tooltip. But the tooltip uses d.name. Seems the d isn't getting down to tooltip for use as d.name I am probably understanding it all wrong. Thanks – Shane G Aug 03 '17 at 15:10