Published
Edited
Feb 8, 2021
1 fork
9 stars
Insert cell
Insert cell
Insert cell
toolTip = d3.select("body").append("div").attr("class", "toolTip")
Insert cell
Insert cell
html`
<style>
.toolTip {
position: absolute;
display: none;
min-width: 30px;
max-width: 240px;
border-radius: 4px;
height: auto;
background: rgba(250,250,250, 0.9);
border: 1px solid #DDD;
padding: 4px 8px;
font-size: .85rem;
text-align: left;
z-index: 1000;
}
</style>
`
Insert cell
Insert cell
Insert cell
md`Draw your data to the svg and add the on mousemove/mousemove and mouseout function to the element. I usually separate them into separate functions so the code is a little easier to navigate when the actions on hover are more complex.`
Insert cell
layout = {
let height = 250

const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
let node = svg.selectAll("circle")
.data(dataPoint)
.join("circle")
.attr("cx", width/2)
.attr("cy", height/2)
.attr("r", 50)
.attr("fill", "#CCC")
.on('mousemove', nodeMouseOver)
.on('mouseout', nodeMouseOut );
// You can also use mouseover if you only want it to run once on enter but the tooltip will stay at the mouse position on enter.

function nodeMouseOver(event, d){
// Get the toolTip, update the position, and append the inner html depending on your content
// I tend to use template literal to more easily output variables.
toolTip.style("left", event.pageX + 18 + "px")
.style("top", event.pageY + 18 + "px")
.style("display", "block")
.html(`Tooltip for <strong>${d.name}</strong>`);
// Optional cursor change on target
d3.select(event.target).style("cursor", "pointer");
// Optional highlight effects on target
d3.select(event.target)
.transition()
.attr('stroke', '#A8234E')
.attr('stroke-width', 3);
}
function nodeMouseOut(event, d){
// Hide tooltip on mouse out
toolTip.style("display", "none"); // Hide toolTip
// Optional cursor change removed
d3.select(event.target).style("cursor", "default");
// Optional highlight removed
d3.select(event.target)
.transition()
.attr('stroke', '#fff')
.attr('stroke-width', 0);
}

return svg.node();
}
Insert cell
d3 = require("d3@6")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more