In the previous codes, we already have some events like dragging the node. Today, let’s add mouseover and mouseout events to the nodes. The codes are listed below and it’s not that difficult. However, I did spend quite a long time getting it to work today.
The reason is that the examples I found on Observable are “this” in the “d3.select(this)” function, and it does not trigger the mouse event. I joined a DVS mentorship program (if you are interested, I highly recommended it), and my mentor helped me to figure out to set up an id of the node and call the id of the node. BUT, when I copied the same method for this Harry Potter file, it did not work.
After many console.log(), I found that the argument we used was (d, i) => mouseOver(d, i) because I put an old version of d3 back then. In D3 version 5 and earlier, the arguments passed to the callback functions were typically in the order of (data, index). In D3 version 6, this was changed. The arguments are now in the order of (event, data).
So pay attention to the version of d3 your example is using and the one in your index.html file.
const node = svg.selectAll(".node")
.data(dataset.nodes)
.enter().append("circle")
.attr("class",d => d.team)
.attr("id", d => `node_${d.id}`)
.attr("r", d => (4-d.group)*7.5)
// add mouse event
.on('mouseover', (event,d) => mouseOver(event,d))
.on('mouseout', (event,d) => mouseOut(event,d))
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended))
function mouseOver(event,d) {
// to see what are the first and second argument
console.log(event, d)
d3.select(`#node_${d.id}`)
.attr("r", 30)
console.log(node.select(`#node_${d.id}`))
}
function mouseOut(event,d) {
console.log(event,d)
d3.select(`#node_${d.id}`)
.attr("r", i => (4-i.group)*7.5)
}
Codes are here.