Why is .on('mousemove') behaving differently?

When doing the FCC projects on data visualization I would always just simply give each path a couple of attributes and by using something like

.on('mousemove', function(d) {
    console.log(d) // This logs a MouseEvent to the connsole
    let data = d['srcElement']['attributes']['data']['value']
    let show = 'This is the data: ' + data
    tooltip.select('text').text(show)
    tooltip.append('text')
}

I would easily have my tooltip working.
But now I am working on my own project and when I do pretty much the same thing, it doesn’t log a mouseevent to the console, but instead just every element from the dataset. So I am not quite sure why that is, any clarification is greatly appreciated!

Or perhaps to be more exact, now that I think about it:
Why does the variable d stand for an element of the dataset in all of the other methods, but in this case is doesn’t?

I assume you’re using D3.js. I think from version 6 onwards, you have to give the “event” (an object with various information about the mouse event) as the first argument in the function, and the data element as the second argument. In your case, the first argument d is being treated as the event.

If you wanna keep the same behaviour, you can downgrade to D3 V5 (https://d3js.org/d3.v5.min.js)

Alternatively, you can restructure your code like this:

.on('mousemove', function(e, d) {
    console.log(d) // This logs a MouseEvent to the connsole
    let data = d['srcElement']['attributes']['data']['value']
    let show = 'This is the data: ' + data
    tooltip.select('text').text(show)
    tooltip.append('text')
}

Where e is the event object and d is the dataset element.

1 Like

Hey Ganesh!
Thanks, I am in fact using d3.js, but I am actually already using v5. When I try to pass in two arguments to the function, it just uses the element of the data, plus its index.

But I guess for now I can also just work with that, so it’s really more of an “I don’t fully understand this” as compared to “I am stuck”.

1 Like

Sorry, my mistake. Upgrade your D3 to V6 to get the functionality you desire, where the first argument is the event object you are trying to log.

To Clarify, in D3 V5:

.on('mousemove' (dataElement, index) => {
 
})

And in D3 V6:

.on('mousemove' (event,  dataElement ) => {
 
})
1 Like

Thanks! Sadly I won’t be able to use this in my project (outside requirements) but that is in fact the solution to the problem in understanding.

1 Like

If you need the event object, this works in V5:

.on('mousemove' (dataElement, index) => {
   let eventObject = d3.event
   console.log(eventObject)
})
1 Like

Amazing, thanks man!

1 Like