Kode_12 Kode_12 - 5 months ago 94
jQuery Question

How can I add a click event to show a tooltip in an NVD3 Pie Chart?

There isn't much documentation on nvd3. In the following plunkr, the tooltip displays on a hover event. That's native to the framework. After reading other stackoverflow questions, one would use someting like the following to display the tooltip via a click versus the hover:

d3.selectAll('.nv-slice')
.on('click', function(d) {
console.log(d.data.label);
});


How can I apply a click event to trigger the tooltip to display?
http://plnkr.co/edit/QYuol3Q10xsA3pziiWGl?p=preview

Answer

So, first of all you have to set a css rule, because the tooltip element does not exist until the first mouse over.

Add to your style.css

.nvtooltip {
    display: none!important;
}

Then you need a callback function after the graph was created, so add the onready attribute to your nvd3 element like this

<nvd3 options="options" data="data" on-ready="callback"></nvd3>

And now you can implement your hack to open and close the tooltip, so add the callback function under your data object inside your app.js

$scope.callback = function(scope, element){
  // Add a click event
  d3.selectAll('.nv-slice').on('click', function(){
    d3.selectAll('.nvtooltip').each(function(){
        this.style.setProperty('display', 'block', 'important');
    });
  });
  // Clear tooltip on mouseout
  d3.selectAll('.nv-slice').each(function(){
    this.addEventListener('mouseout', function(){
        d3.selectAll('.nvtooltip').each(function(){
            this.style.setProperty('display', 'none', 'important');
        });
    }, false);
  });
  // we use foreach and event listener because the on('mouseout')
  // was overidding some other function
};

Here you are: http://plnkr.co/edit/7WkFK2LqzDyDmnIt2xlf?p=preview