'D3 / JavaScript find nearest element from mouse position

I am trying to show the nearest data point and its text when you hover over path element (in pink color in the example) using D3 / Javascript.

JS Fiddle: https://jsfiddle.net/qkcsrt7p/

I tried searching for examples but I haven't got anything that can give me the nearest data point to the mouse position. Has anyone tried similar functionality before?

Code so far:

d3.selectAll("g text.label")
  .on('mouseover', function (d) {
    tooltip.transition().duration(200)
      .style('opacity', .9)
    var toolTipText = "<span>" + this.textContent + "</span>";
    tooltip.html(toolTipText)
      .style('left', (d3.event.pageX - 35) + 'px')
      .style('top', (d3.event.pageY - 30) + 'px');
  })
  .on('mouseout', function (d) {
    tooltip.transition().duration(200)
      .style('opacity', 0);
    tooltip.html("");
  })

d3.selectAll("path")
  .on('mouseover', function (d) {
    var elements = document.elementsFromPoint(d3.event.pageX, d3.event.pageY);
    console.log(elements);
  })
  .on('mouseout', function (d) {

  })


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source