Last active
September 20, 2017 21:47
-
-
Save mmazanec22/ef8297c0b0f9d07b3eecc0c39ce92343 to your computer and use it in GitHub Desktop.
Tooltip That Doesn't Collide With Edges
This file contains 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="https://d3js.org/d3.v3.min.js"></script> | |
<script type="text/javascript" src='./tooltip.js'></script> | |
<link rel="stylesheet" type="text/css" href="./styles.css"> | |
</head> | |
<body> | |
<svg> | |
</svg> | |
</body> | |
</html> |
This file contains 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
html, body { | |
height: 100%; | |
width: 100%; | |
} | |
svg { | |
height: 100%; | |
width: 100%; | |
} |
This file contains 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
document.addEventListener('DOMContentLoaded', () => { | |
makeToolTip(); | |
}); | |
function makeToolTip() { | |
const svg = d3.select('svg'); | |
const tooltip = d3.select('body').append('div') | |
.attr('class', 'tooltip') | |
.style('position', 'absolute') | |
.style('z-index', '1'); | |
tooltip.append('text') | |
.text('tooltip') | |
.attr('text-anchor', 'middle') | |
.style('color', 'pink'); | |
svg | |
.on('mousemove', () => { | |
moveToolTip(tooltip); | |
}) | |
.on('mouseout', () => { | |
tooltip.style('display', 'none'); | |
}); | |
} | |
function moveToolTip(tooltip) { | |
const svg = d3.select('svg'); | |
tooltip.style('display', 'unset'); | |
const svgDimensions = svg.node().getBoundingClientRect(); | |
const eventXRelToScroll = d3.event.pageX - window.scrollX; | |
const eventYRelToScroll = d3.event.pageY - window.scrollY; | |
let tipX = (eventXRelToScroll) + 15; | |
let tipY = (eventYRelToScroll) + 10; | |
const tooltipDimensions = tooltip.node().getBoundingClientRect(); | |
tipX = (eventXRelToScroll + tooltipDimensions.width + 10 > svgDimensions.right) ? | |
tipX - tooltipDimensions.width - 15 : tipX; | |
tipY = (eventYRelToScroll + tooltipDimensions.height + 10 > svgDimensions.bottom) ? | |
tipY - tooltipDimensions.height - 10 : tipY; | |
tooltip | |
.transition() | |
.duration(10) | |
.style('top', `${tipY}px`) | |
.style('left', `${tipX}px`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment