Problem with D3

Hello, I am doing the Data Visualization Projects - Visualize Data with a Bar Chart | Learn |

I am adding listeners to the bars with the on method. As per javascript in the callback function, this should be associated with the element listening to the event but it came out to be the window object. (on line 77)

I don’t know what’s happening.

Here’s the link - Codepen

Arrow functions don’t bind this. So, the problem is here

    .on("mouseover", (e) => {
      console.log(e, this);

An easier way to do this is to join your two calls to bar into one and add the mouse listeners as you loop over the data because with your version of D3, the on signature is .on('mouseover', (event, datum) ...) and you have the current element’s datum available when you define the function (via datum) instead of trying to grab it at run time via attributes.

If you try to fix the runtime route, convert the function to a regular (non arrow) function, and you will need to add the select/enter/data part to the second bars call as well, but it still may not work.

Thanks, didn’t knew this difference between the two function declarations.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.