← Back to all snippets
JAVASCRIPT

Dynamically Positioning a Tooltip Relative to Another Element

Implement a dynamic tooltip positioning mechanism using `getBoundingClientRect` to accurately place elements relative to others in the DOM.

function positionTooltip(tooltipElement, targetElement, offset = 10) {
  const targetRect = targetElement.getBoundingClientRect();
  const tooltipRect = tooltipElement.getBoundingClientRect();

  // Calculate tooltip position (e.g., top-center of the target)
  let top = targetRect.top - tooltipRect.height - offset;
  let left = targetRect.left + (targetRect.width / 2) - (tooltipRect.width / 2);

  // Ensure tooltip doesn't go off-screen (basic check)
  if (top < 0) { // If it's above the viewport, position below
    top = targetRect.bottom + offset;
  }
  if (left < 0) { // If it's too far left, align left with target
    left = targetRect.left;
  }
  if (left + tooltipRect.width > window.innerWidth) { // If too far right, align right
    left = targetRect.right - tooltipRect.width;
  }

  // Apply calculated styles (position fixed for viewport-relative positioning)
  Object.assign(tooltipElement.style, {
    position: 'fixed',
    top: `${top}px`,
    left: `${left}px`,
    zIndex: '1000' // Ensure it's on top
  });
}

// Example Usage (assuming you have HTML elements with these IDs):
// <button id="myButton">Hover me for info</button>
// <div id="myTooltip" style="display: none; background: #333; color: white; padding: 5px; border-radius: 3px;">This is a tooltip!</div>

const myButton = document.getElementById('myButton');
const myTooltip = document.getElementById('myTooltip');

if (myButton && myTooltip) {
  myButton.addEventListener('mouseenter', () => {
    myTooltip.style.display = 'block'; // Make visible first to get dimensions
    positionTooltip(myTooltip, myButton);
  });

  myButton.addEventListener('mouseleave', () => {
    myTooltip.style.display = 'none';
  });
}
How it works: This snippet provides a function to dynamically position one DOM element (like a tooltip) relative to another target element. It leverages `getBoundingClientRect()` to get the precise size and position of both elements relative to the viewport. Based on these measurements, it calculates new `top` and `left` CSS properties for the tooltip, ensuring it appears correctly, even adding basic viewport collision detection. The `position: fixed` style is used for consistent positioning irrespective of page scrolling. This pattern is essential for creating floating UI elements like tooltips, popovers, and context menus.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs