1

I have a Stackblitz here - https://stackblitz.com/edit/ng-graph-tooltip?file=src%2Fapp%2Fapp.component.html

I have a mouseover event when hovering over the bars

I trying to get the width and x pos of the bar when over it so I can position the tooltip

How can I get the width and x pos when over the bar.

Is this a problem with 'this' in Angular

d3.selectAll('.bar-opacity').on("mouseover", (d:any) => {

    const xPos = d3.select(this).attr('x');
    const rectWidth = d3.select(this).attr('width');

    console.log(xPos)

    let html = ''
      html += '<div class="">'+d.color+'</div>'
      html += '<div class="tooltip-block">'+d.day+'</div>'

    d3.select('.chart-tooltip')
      .style("left", d3.event.pageX + 5 + "px")
      .style("top", d3.event.pageY - 25 + "px")
      .html(html)

    d3.select('.chart-tooltip').style("display", null)
    })

    .on("mouseout", ()=>{
    d3.select('.chart-tooltip').style("display", "none")
      .transition()
      .duration(500)
    }) 
ttmt
  • 5,822
  • 27
  • 106
  • 158
  • First thing I noticed - Do not use arrow function in D3 event handlers. Try using it as a normal function to use `this`. – CRayen Nov 20 '18 at 12:48
  • This works here but in my actual code I'm using variables outside this function like `this.margin.top` in this example this doesn't work when the function is like that - https://stackblitz.com/edit/ng-graph-tooltip-jqa9gf?file=src%2Fapp%2Fbar-chart.ts – ttmt Nov 20 '18 at 13:13
  • What is the problem? Using a normal function like you did in the stackblitz allows you to successfully get the width and pos... – Zim Nov 20 '18 at 13:23
  • Using a normal function I cant access things like `this.margin.top`. I'll post a separate question – ttmt Nov 20 '18 at 13:27
  • As explained here: https://stackoverflow.com/questions/53204937/d3-get-x-position-on-mouseover/53205876#53205876 you can use an arrow function with the third argument of the callback `(datum,index,elements) => { const coords = d3.mouse(elements[index]); };` – David Lemon Nov 20 '18 at 14:03

0 Answers0