Search code examples
jquerytooltip

JQuery keep tooltip in viewport


I am trying to keep a tooltip in viewport. The code seems to work except when the page is scrolled.

Can someone look at this?

<div class="test"></div>
<p><a href="#" rel="tooltip" title="Cool tooltip with long name">Cool tooltip</a></p>
<p>or <a href="#" rel="tooltip" title="Another tooltip">Another tooltip</a></p>
<div class="test"></div>

http://jsfiddle.net/QvLwd/5/


Solution

  • In your case you should change this line:

    pos_top  = target.offset().top - tooltip.outerHeight() - 20 - $(window).scrollTop();
    

    to:

    pos_top  = target.offset().top - tooltip.outerHeight() - 20; // initial top relative to BODY
    

    and this:

    if( pos_top < 0 )
    

    to:

    if( pos_top < $(window).scrollTop() )
    

    (and similar changes for pos_left)

    It's because target.offset() gives you position relative to your BODY element and your BODY element's position is affected by the scroll (i.e. BODY expands above the top of the window when it is scrolled).

    In other words: because you are adding tooltip element to the BODY, you should not adjust it's position by $(window).scrollTop() when calculating tooltip's position because it will be adjusted by it anyway (through it's parent's, i.e. BODY's, position). All you need to do, is check if tooltip's initial position is above the window, and move it down in this case - everything in BODY that has top coordinate < $(window).scrollTop() will be hidden (at least partially).