Skip to content

Instantly share code, notes, and snippets.

@rwbrockhoff
Created March 19, 2019 00:58
Show Gist options
  • Save rwbrockhoff/d45cf5351d7b42e40bfa98a7a00d46c6 to your computer and use it in GitHub Desktop.
Save rwbrockhoff/d45cf5351d7b42e40bfa98a7a00d46c6 to your computer and use it in GitHub Desktop.
// Display and position tooltip
tooltipEl.style.opacity = 1;
tooltipEl.style.position = 'absolute';
const padding = 10;
const position = this._chart.canvas.getBoundingClientRect();
// Ensure Tooltip stays in view at far-left and far-right edges
const toolWidth = tooltipModel.width;
const graphWidth = lineGraph.width;
const caretPosition = tooltipModel.caretX;
const maxPosition = graphWidth - toolWidth;
const normalizedPosition = caretPosition + position.left;
if (caretPosition >= maxPosition) {
//Move tooltip left by the excess amount with padding
const xDif = caretPosition - maxPosition;
tooltipEl.style.left = normalizedPosition - (xDif + padding) + 'px';
} else {
//Return normal tooltip position
tooltipEl.style.left = `${normalizedPosition}px`;
}
//Ensure Tooltip stays in view at top and bottom most positions
const toolHeight = tooltipModel.height;
const graphHeight = lineGraph.height;
const caretYPosition = tooltipModel.caretY;
const maxYPosition = graphHeight - toolHeight;
const normalizedYPosition = caretYPosition + position.top;
if (caretYPosition >= maxYPosition) {
const yDif = caretYPosition - maxYPosition;
tooltipEl.style.top = normalizedYPosition - (yDif + padding) + "px";
} else {
tooltipEl.style.top = `${normalizedYPosition}px`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment