CSS dynamic position of tooltip on hover with jQuery
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.
Narazana
Updated on June 19, 2022Comments
-
Narazana almost 2 years
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 screenIf 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 visibleThank you.
Update demo link
here's the complete result: http://jsfiddle.net/Qkwm8/3/
-
kobe almost 13 yearsdo you want to flip the tooltip to the left if there no window space on right hand side,
-
-
Vincent Ramdhanie almost 13 years@Narazana You can do it in a similar manner to the way the left worked. Instead use the height() function. I'll edit the answer with an example.
-
Narazana almost 13 yearsThanks, Vicent. I finally did it. I just updated the question to include the latest update demo at jsfiddle.net/Qkwm8/3
-
innovation over 9 years@VincentRamdhanie Dear Vincent Ramdhanie can you check my question. STACKOVERFLOW