In previous versions it was possible to retrieve the index i by:
selection.on("click", function(d,i){...}
However, that does not seem to work anymore in the latest version since the first parameter is always the event object. How can I get the index of the datum in the listener function?
let data = [2,5,8,9]
d3.select("body").selectAll("p")
.data(data)
.enter()
.append("p")
.text(d=>d)
.on("mouseover", function(e,d,i){
//console.log(e); --> event
console.log(d);
console.log(i);
// i should be the index of the hovered element
})
<script src="https://d3js.org/d3.v6.min.js"></script>
When a specified event is dispatched on a selected element, the specified listener will be evaluated for the element, being passed the current event (event) and the current datum (d), with this as the current DOM element (event.currentTarget).
Official documentation: https://github.com/d3/d3-selection/blob/v2.0.0/README.md#selection_on