0

I have a tooltip element which is displayed when hovering over certain elements.

I would like the tooltip to be positioned above the normal element as expected but in the case where the tooltip is too large and escapes the window, I need this to NOT happen.

How can I have an element which is absolutely positioned and also never displays out of view?

Edit: Preferably using CSS...

Titus
  • 720
  • 8
  • 23
  • If the tooltip follows the mouse, then just set the width to its current width - half the width + pixels the mouse is away from the left or right. – Lugia101101 Nov 09 '13 at 14:57
  • I'd rather its width didn't change. I should be more clear - it's not that its width is too large, it's that when you hover over an element that is at the very right/left/top.. etc of the page - the tooltip is shown outside of the viewport. – Titus Nov 09 '13 at 15:11
  • So do you mean the tooltip doesn't show, or positions itself to fit? – Lugia101101 Nov 09 '13 at 15:18
  • 1
    You will need to use JS to get a good solution. – justisb Nov 09 '13 at 15:29

1 Answers1

0

Following the idea presented here: How to tell if a DOM element is visible in the current viewport?

I'd got with:

function elementInViewport(el) {
  var top = el.offsetTop;
  var left = el.offsetLeft;
  var width = el.offsetWidth;
  var height = el.offsetHeight;

  while(el.offsetParent) {
    el = el.offsetParent;
    top += el.offsetTop;
    left += el.offsetLeft;
  }

  return (
    top >= window.pageYOffset &&
    left >= window.pageXOffset &&
    (top + height) <= (window.pageYOffset + window.innerHeight) &&
    (left + width) <= (window.pageXOffset + window.innerWidth)
  );
}

var tooltip = $(".tooltip");
tooltip.show(); //we must make it visible in order to perform the test on the next line
if(!elementInViewport(tooltip)) {
  tooltip.hide();
}
Community
  • 1
  • 1
silicakes
  • 4,490
  • 2
  • 23
  • 33