-
create a new project
-
set up index.html, main.js, d3.js
-
Start with the four circles that you used in the previous lesson. Delete the event handlers. Copy the code below into the main.js file.
const svg = d3.select('body') .append('svg') .attr('width', 300) .attr('height', 300); 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' }]; const circles = svg.selectAll('circle') .data(dataset) .enter() .append('circle'); circles .attr('cx', d => d.cx) .attr('cy', d => d.cy) .attr('r', d => d.r);
Add circle to the right of the first circle.
circles.on('mouseover', (data, index, nodes) => {
svg.append('circle')
.attr('cx', '125')
.attr('cy', '25')
.attr('r', '25');
});
circles.on('mouseover', (data) => {
svg.append('circle')
.attr('cx', () => data.cx + 100)
.attr('cy', () => data.cy)
.attr('r', '25');
});
When you move the mouse off of the left circle, the right circle will disappear.
- add id for the new circle
- create a mouseout event handler to delete the new circle by selecting the id
circles.on('mouseover', (data) => {
svg.append('circle')
.attr('cx', () => data.cx + 100)
.attr('cy', () => data.cy)
.attr('r', '25')
.attr('id', 'removeMe');
});
Use the inspector to make sure the id is attached.
circles.on('mouseout', () => {
d3.select('#removeMe')
.remove();
});
circles.on('mouseover', (data) => {
svg.append('text')
.attr('x', () => data.cx + 100)
.attr('y', () => data.cy)
.text(data.color)
.attr('id', 'removeMe');
});
-
This is a shortcut that replaces the plus sign
-
it is the same as 'color: ' + data.color
-
must use back-tick, which is in the upper left of the keyboard
circles.on('mouseout', () => { d3.select('#removeMe') .remove(); });
adjust placement of text
Add in additional text and adjust placement to make it into a tooltip.
.text(`color:${data.color} x:${data.cx} y:${data.cy}`)
-
nodes[index]is the current circle that is selected -
apply style to current circle
circles.on('mouseover', (data, index, nodes) => { d3.select(nodes[index]) .style('fill', data.color);
In mouseout, adjust style back to black.
circles.on('mouseout', (data, index, nodes) => {
d3.select(nodes[index])
.style('fill', 'black');
-
set all circles opacity to 0.25
-
set selected circle opacity back to 1
circles.on('mouseover', (data, index, nodes) => { circles .attr('opacity', '0.25'); d3.select(nodes[index]) .style('fill', data.color) .attr('opacity', '1');
On mouseout, reset opacity.
circles.on('mouseout', (data, index, nodes) => {
circles
.attr('opacity', '1');
d3.select(nodes[index])
.style('fill', 'black');
d3.select('#removeMe')
.remove();
});





