Skip to content

Instantly share code, notes, and snippets.

@mmazanec22
Last active September 20, 2017 21:47
Show Gist options
  • Save mmazanec22/ef8297c0b0f9d07b3eecc0c39ce92343 to your computer and use it in GitHub Desktop.
Save mmazanec22/ef8297c0b0f9d07b3eecc0c39ce92343 to your computer and use it in GitHub Desktop.
Tooltip That Doesn't Collide With Edges
<!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>
html, body {
height: 100%;
width: 100%;
}
svg {
height: 100%;
width: 100%;
}
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