Federico C
Federico C

Reputation: 125

How to apply tooltips for dc.js chart after chart is rendered

I have multiple row charts (crossfilter + dc) and I want to customize the tooltip using d3-tip.

So basically the relevant code is:

rowtip = d3.tip()
    .attr('class', 'd3-tip')
    .offset([-10, 0])
    .html(function (d) { return d.key + ": "  + d.value; });

...my dc charts ...

... then at the bottom of my script tags ...

d3.selectAll('g.row').call(rowtip);
d3.selectAll('g.row').on('mouseover', rowtip.show);

The code seems work, but the mouseover event doesn't get triggered automatically and the tooltips don't get displayed when the page loads.

But If I run the last line (mouseover) on the console, then everything works as expected.

enter image description here

So my question would be how can I make sure the mouseover event gets triggered when the page loads. I tried Jquery $(document).ready(....), but that didn't work.

It has to have something to do with the order in which the elements are loaded... I guess. But I'm not an expert in javascript and much less in d3.

Thanks in advance.

Upvotes: 4

Views: 2327

Answers (3)

Gordon
Gordon

Reputation: 20140

Your way works fine but here is the idiomatic dc.js way to do it:

chart.on('pretransition.add-tip', function(chart) {
    chart.selectAll('g.row')
        .call(rowtip)
        .on('mouseover', rowtip.show)
        .on('mouseout', rowtip.hide);
});

The pretransition event fires after the chart is rendered or redrawn. add-tip is an event namespace to avoid interfering with anything else which may be watching this event.

chart.selectAll selects only items within the chart, to avoid accidental tooltips elsewhere in the page.

Upvotes: 6

Federico C
Federico C

Reputation: 125

So I was able to solve this by using jquery after all. Seems a bit hacky, but it does what I need.

Basically I am forcing the call of the d3-tip function on mouseover of the html body.

var rowtip = d3.tip()
    .attr('class', 'd3-tip')
    .offset([-10, 0])
    .html(function(d){return d.key;}) 

$('body').on('mouseover', function(){

    d3.selectAll('g.row')
        .call(rowtip)
        .on('mouseover', rowtip.show)
        .on('mouseout', rowtip.hide);     

});

Upvotes: 1

Anupam Khasia
Anupam Khasia

Reputation: 89

Here seems similar to your requirement, check it

http://bl.ocks.org/phil-pedruco/9032348

Upvotes: 1

Related Questions