How to add a click event on nvd3.js graph

Just found out that this works as well (at least for multibar charts):

chart.multibar.dispatch.on("elementClick", function(e) {
    console.log(e);
});

I had to look at the source in src/multibar.js to find out; since it's there, I guess this is the way it was intended to be done. However, I second what Alex said in his answer: the lack of documentation for NVD3 is a really big disadvantage. Which is sad because the general idea of the project is great: giving us the power of D3 without going into all the details...


There are three key points here.

1) No documentation means you have to go through the source code.

2) All graphs have a tooltip, which means events are already firing in the source code.

3) Use the configuration object (in the Documentation) as a road map of the source code.

ie.

var config = {chart: {type: 'multiChart',xAxis:{},yAxis{}}

Open the nvd3/nv.d3.js file

CTRL+F+ the chart type. In this case it is 'multiChart'.

You will see nv.models.multiChart.

Scroll down to find the tooltip events and you will find the needed documentation.

lines1.dispatch.on('elementMouseout.tooltip', function(evt) {tooltip.hidden(true) });
stack1.dispatch.on('elementMouseout.tooltip', function(evt) {tooltip.hidden(true) });
bars1.dispatch.on('elementMouseout.tooltip', function(evt) {tooltip.hidden(true) });

Therefore, to write your own event...

var config = {chart: {type: 'multiChart',
               bars1: {
                dispatch:{
                    elementClick:function(e){//do Stuff}
                },
               xAxis:{},yAxis{}
              }

I was running into the same issue and was about to dump NVD3 all together because of the lack of documentation... What you need to do is add a callback function to addGraph(). Also note the d3.selectAll() instead of d3.select().

Good Luck.

nv.addGraph(function() {
     var chart = nv.models.multiBarHorizontalChart()
         .x(function(d) { return d.label })
         .y(function(d) { return d.value })
         .margin({top: 5, right: 5, bottom: 5, left: 5})
         .showValues(false)
         .tooltips(true)
         .showControls(false);

     chart.yAxis
         .tickFormat(d3.format('d'));

     d3.select('#social-graph svg')
         .datum([data])
       .transition().duration(500)
         .call(chart);

       nv.utils.windowResize(chart.update);

       return chart;
     },function(){
          d3.selectAll(".nv-bar").on('click',
               function(){
                     console.log("test");
           });
      });