Mouse Events

D3 supports all JavaScript mouse events. Learn how to detect hover events with D3.

We will use mouse events to help us detect when the reader is hovering over a dot. If they are, we are going to move the tooltip element above the dot. The contents of the tooltip will need to be updated to show the data joined to the dot.

Adding mouse events

A mouse event called mouseenter can be used to detect when the mouse is hovering over an element. We will be using this event to help us create our UI. In the script section, search for the section in our code where we draw the dots.

At the end of this chain, we will add the on() function to listen for the mouseenter event.

Press + to interact
// Draw circles
ctr.selectAll('circle')
.data(dataset)
.join('circle')
.attr("cx", d => xScale(xAccessor(d)))
.attr("cy", d => yScale(yAccessor(d)))
.attr('data-temp', yAccessor)
.attr("r", 5)
.attr("fill", 'red')
.on('mouseenter', function(e, datum) {
console.log(datum)
})

The second argument of the on() function is a callback function. One thing we should note is that we are not using an arrow function. This is because we want to use the this keyword. The this keyword in the function will tell us which dot the mouse is hovered over. Even though we are listening for the event on the entire selection, D3 is smart enough to provide us with information about a specific dot.

In addition, we are going to need the data joined to the element. We are accepting it as one of the arguments for the callback function. ...

Access this course and 1400+ top-rated courses and projects.