Skip to content

Instantly share code, notes, and snippets.

@mohnish
Last active February 27, 2024 07:15
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 mohnish/12177971853ce3284db6445b78b73e82 to your computer and use it in GitHub Desktop.
Save mohnish/12177971853ce3284db6445b78b73e82 to your computer and use it in GitHub Desktop.
Check if an element is being displayed in the current viewport
// `element` - the reference from the references section
function checkVisibilityAndShowTooltip(element, tooltipElement) {
const rect = element.getBoundingClientRect();
const isVisible = rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth);
// Update tooltip visibility based on preference
if (isVisible) {
element.dataset.isVisible = 'true'; // Or use a custom class
} else {
tooltipElement.style.display = 'block'; // Or use a custom class or property
}
}
// Usage:
const element = document.querySelector('#cite_note-8'); // this is the reference ID
const tooltip = document.querySelector('your-tooltip-id-here');
// Add event listeners for rechecking visibility on scroll or resize:
window.addEventListener('scroll', () => checkVisibilityAndShowTooltip(element, tooltip));
window.addEventListener('resize', () => checkVisibilityAndShowTooltip(element, tooltip));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment