1

I have a plunker here - https://plnkr.co/edit/iOGJUosvruW9KV1FF9lp?p=preview

On mouseover of the bars I want to show a tooltip

At the moment it move with the mouse but I want it to be a set position above the bars I'm over.

How do I get the x and y position of the bar I'm over

I have tried, but I get errors.

console.log(d3.mouse(this)[0]); 
ttmt
  • 5,822
  • 27
  • 106
  • 158

1 Answers1

2

As explained in MDN:

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

Arrow functions are introduced to be pure functions, and that's the reason why they don't have this kind of context variables.

Just convert the arrow function to a regular one. I forked your plunker:

https://plnkr.co/edit/3Y4T0JZ42eH2wb42tpsg?p=preview

d3.selectAll('.bar').on("mouseover", function(){
   console.log(d3.mouse(this)[0]);
   d3.select('.chart-tooltip').style("display", null)
})

UPDATE:

You can also replace this with the global d3.event.target and keep the function as an arrow function.

d3.selectAll('.bar').on("mouseover", () => {
  console.log(d3.mouse(d3.event.target)[0]);
  d3.select('.chart-tooltip').style("display", null)
})

UPDATE II:

Gerardo Furtado proposed to use the third argument of the callback to get the html element. Also a good solution, as d3.event can be problematic in certain situations.

d3.selectAll('.bar').on("mouseover", (datum,index,elements) => {
  console.log(d3.mouse(elements[index])[0]);
  d3.select('.chart-tooltip').style("display", null)
})
David Lemon
  • 1,560
  • 10
  • 21