Search code examples
javascriptd3.jstooltip

d3.js: tooltip and attribute change on mouseover


I've integrated tooltips by Caged in my d3 visualization (Fiddle). They are called simply with

.on("mouseover", tip.show)
.on("mouseout", tip.hide)

Now I've found I can't add other mouseover functionalities such as changing the size and colour of the object I'm pointing the mouse at. Either the tooltips or the attribute changes are shown when I try something like this:

on("mouseover", function(d){
 tip.show;
 d3.select(this).attr("r", 10).style("fill", "orange");
})
.on("mouseout", function(d){
 tip.hide;
 d3.select(this).attr("r", 6).style("fill", "red");
})

How can I show both?


Solution

  • You need to call the tooltip functions:

    .on("mouseover", function(d){
      tip.show(d);
      d3.select(this).attr("r", 10).style("fill", "orange");
    }).on("mouseout", function(d){
      tip.hide(d);
      d3.select(this).attr("r", 6).style("fill", "red");
    })
    

    tip.show and tip.hide are functions and adding parentheses after the name means that you're calling them. This isn't necessary when not using an anonymous function (i.e. function() { ... }) because D3 knows that a function is being passed and should be called (i.e. evaluated) at runtime. In short, D3 calls the function passed as an argument automatically.