ttmt
ttmt

Reputation: 4984

D3 - Select element in this svg?

I have a codepen here - https://codepen.io/anon/pen/yvgJKB

I have two d3 charts with different data.

I want to have tooltips on the bars so when you rollover them it shows the value.

I want the tooltip to be separate html in the svg cos the actual charts are responsive and I dont want the tooltips to scale with the svg.

The tooltip works as expected in the top chart.

In the bottom chart the tooltip appears in the top chart.

I think this is becasue the let tooltip = d3.select('.tooltip').append("div") is selecting the first tooltip which is in the first chart.

The charts and tooltip is dynamically created.

This there a way in the D3 to say d3.select('.tooltip') in this svg something like d3.select(this)('.tooltip')

let tooltip = d3.select('.tooltip').append("div")
    .attr("class", "tip")
    .style("display", "none")
    .attr("fill", "grey");

Upvotes: 0

Views: 96

Answers (2)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

There is a lot of unnecessary repetition in your code.

Create the tooltip div only once. Also, since you are creating the div in your D3 code, you don't need any div with the tooltip class in your HTML. Remove both.

Besides that, use d3.event.pageX and d3.event.pageY to position your tooltip div anywhere in the page. A single tooltip div can be used to show the tooltip to any number of SVGs you have on that page.

Here is your updated CodePen: https://codepen.io/anon/pen/KQaBvE?editors=0010

Upvotes: 1

Ryan Morton
Ryan Morton

Reputation: 2695

Tooltips should be created separately by selecting different charts (or some other unique marker) and given unique variable names within the same scope:

let tooltip1 = d3.select('.chart1').append("div")
    .attr("class", "tip")
    .style("display", "none")
    .attr("fill", "grey");

let tooltip2 = d3.select('.chart2').append("div")
    .attr("class", "tip")
    .style("display", "none")
    .attr("fill", "grey");

https://codepen.io/mortonanalytics/pen/BYpwaz

Upvotes: 1

Related Questions