Search code examples
javascriptd3.jstooltip

d3.js table tooltip not disappearing


Right now, when I hover over an element in my co-occurrence matrix (similar to the les miserables example by mike bostick) a tooltip appears with a table of information. To generate the table and append it to the div tooltip I"m using the following code:

function tabulate(data, columns) {
  var table = div.append("table")
      thead = table.append("thead"),
      tbody = table.append("tbody");

  // append the header row
  thead.append("tr")
      .selectAll("th")
      .data(columns)
      .enter()
      .append("th")
          .text(function(column) { return column; });

  // create a row for each object in the data
  var rows = tbody.selectAll("tr")
      .data(data)
      .enter()
      .append("tr");

  // create a cell in each row for each column
  var cells = rows.selectAll("td")
      .data(function(row) {
          return columns.map(function(column) {
              return {column: column, value: row[column]};
          });
      })
      .enter()
      .append("td")
          .text(function(d) { return d.value; });

  return table;

}

This works perfectly and the table is generated every time I hover over an element. My mousemove, mouseover, and mouseout functions are as follows:

function mousemove(d) {
    tabulate(nodes[d.x].tableInfo[d.y], ['site', 'win1', 'bid1', 'win2', 'bid2'])
    div
      .style("left", (d3.event.pageX) + "px")
      .style("top", (d3.event.pageY) + "px" )
}

function mouseover(p) {
    div.transition()
        .duration(300)
        .style("opacity", 1);
    d3.selectAll(".row text").classed("active", function(d, i) { return i == p.y; });
    d3.selectAll(".column text").classed("active", function(d, i) { return i == p.x; });
}

function mouseout() {
    div.transition()
        .duration(300)
        .style("opacity", 1e-6);
    d3.selectAll("text").classed("active", false);
}

Now the problem I'm having is that every time I hover over the element, the table is generated again and the old one is not removed. Is there any way to have the old element deleted on mouseout? Thanks.


Solution

  • Just remove the old table before you add a new one:

    function tabulate(data, columns) {
      div.select("table").remove();
      var table = div.append("table"),
      ect