Skip to content

Instantly share code, notes, and snippets.

@dfadler
Created June 13, 2020 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfadler/805b6569884089d413655c6e88afd4ae to your computer and use it in GitHub Desktop.
Save dfadler/805b6569884089d413655c6e88afd4ae to your computer and use it in GitHub Desktop.
tooltip function d3
function onMouseMove() {
const mousePosition = d3.mouse(this)
const hoveredDate = xScale.invert(mousePosition[0])
const getDistanceFromHoveredDate = d => Math.abs(xAccessor(d) - hoveredDate)
const closestIndex = d3.scan(dataset, (a, b) => (
getDistanceFromHoveredDate(a) - getDistanceFromHoveredDate(b)
))
const closestDataPoint = dataset[closestIndex]
const closestXValue = xAccessor(closestDataPoint)
const closestYValue = yAccessor(closestDataPoint)
const formatDate = d3.timeFormat("%B %A %-d, %Y")
tooltip.select("#date")
.text(formatDate(closestXValue))
const formatTemperature = d => `${d3.format(".1f")(d)}°F`
tooltip.select("#temperature")
.html(formatTemperature(closestYValue))
const x = xScale(closestXValue)
+ dimensions.margin.left
const y = yScale(closestYValue)
+ dimensions.margin.top
tooltip.style("transform", `translate(`
+ `calc( -50% + ${x}px),`
+ `calc(-100% + ${y}px)`
+ `)`)
tooltip.style("opacity", 1)
tooltipCircle
.attr("cx", xScale(closestXValue))
.attr("cy", yScale(closestYValue))
.style("opacity", 1)
}
function onMouseLeave() {
tooltip.style("opacity", 0)
tooltipCircle.style("opacity", 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment