Change graph focus based on mouse location.
onkeywordmouseoverkeywordmouseoutkeyword- JavaScript fat arrow function syntax
=> - using
nodes[index]as alternative tothis
Question: what event did we use with the radio buttons in the previous lesson?
- create new project called mouse-events
- create
index.html - put
d3.jsintojssub-directory - create
main.js - link
index.htmltod3.jsandmain.js
Create svg viewport with a size of 300x300.
- select body
- append svg
- add attributes for width and height
Create circle with a center of 25, 25 and radius of 25.
We will create multiple circles from a dataset.
Start with data for one circle.
const dataset = [
{ cx: 25, cy: 25, r: 25, color: 'red' }
];
Circle has no attributes and will not appear in the viewport. You can check it in the inspector.
const circles = svg.selectAll('circle')
.data(dataset)
.enter()
.append('circle');
const dataset = [
{ cx: 25, cy: 25, r: 25, color: 'red' },
{ cx: 25, cy: 100, r: 25, color: 'green' },
{ cx: 25, cy: 175, r: 25, color: 'blue' },
{ cx: 25, cy: 250, r: 25, color: 'orange' }];
With four objects of data, four circles will be created, each circle bound to one data object.
Circles are still not visible as the attributes for the circles have not been set.
Using fat arrow functions, which replaces function() in this exercise.
The following is a shorter way or writing function(d) { return d.cx }.
circles
.attr('cx', d => d.cx)
.attr('cy', d => d.cy)
.attr('r', d => d.r);
The two keywords are:
-
on
-
mouseover
circles.on('mouseover', () => { console.log('mouse over circle'); });
Check that you get the correct message in the console each time you move the mouse over the circle.
circles.on('mouseover', (data, index, nodes) => {
});
const currentCircle = d3.select(nodes[index])
circles.on('mouseover', (data, index, nodes) => {
const currentCircle = d3.select(nodes[index]);
currentCircle
.transition()
.attr('cx', '275')
.transition()
.attr('cx', '25');
});
circles.on('mouseover', (data, index, nodes) => {
const currentCircle = d3.select(nodes[index]);
currentCircle
.transition()
.attr('cx', '275')
.style('fill', 'green')
.transition()
.attr('cx', '25')
.style('fill', 'black');
});
Chain the new transitions to previous transition.
.style('fill', 'black')
.transition()
.attr('opacity', '0')
.transition()
.attr('opacity', '1');
});





