Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS dynamic position of tooltip on hover with jQuery

I'm writing a simple tooltip that can hold HTML tags. Please check http://jsfiddle.net/Qkwm8/ for the demo.

I want the tooltip box to show properly regardless of the position of element, in this case <a>, that shows tooltips on mouseover event.

The tooltips are shown fine except when <a> floats right (or is at the end of the line) or at the bottom of the screen where it doesn't show properly, it appears off the screen

If the <a> floats right, or at the end of the line, or is at the bottom of the screen, I want the tooltip to change position so it remains visible

Thank you.

Update demo link

here's the complete result: http://jsfiddle.net/Qkwm8/3/

like image 899
Narazana Avatar asked May 19 '11 15:05

Narazana


1 Answers

You can use the document width to check how wide the html document is and adjust the left position accordingly. Say:

    //set  the left position
    var left = $(this).offset().left + 10;
    if(left + 200 > $(document).width()){
        left = $(document).width() - 200;   
    }

I used 200 here because you are setting your tooltip to 200px wide. Something similar can be done with height.

There is also a window width but I always get confused about the difference so you should check which one gives you better results.

An example of the bottom of the page is:

   //set the height, top position
    var height = $(this).height();
    var top = $(this).offset().top;
    if(top + 200 > $(window).height()){
        top = $(window).height() - 200 - height;
    }

Again, using 200 since you are setting your tooltip to 200px height.

like image 110
Vincent Ramdhanie Avatar answered Sep 16 '22 17:09

Vincent Ramdhanie