Created
June 13, 2020 05:48
-
-
Save dfadler/805b6569884089d413655c6e88afd4ae to your computer and use it in GitHub Desktop.
tooltip function d3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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