JSFiddle - React, Tailwind, and code Playground
HTML
<div id="body">
surrounding text
<div id="pane" style="overflow: auto; height: 400px; width: 400px;">
lots and lots of text here<br/>
lots and lots of text here<br/>
lots and lots of text here<br/>
lots and lots of text here<br/>
lots and lots of text here<br/>
lots and lots of text here<br/>
lots and lots of text here<br/>
lots and lots of text here<br/>
lots and lots of text here<br/>
lots and lots of text here<br/>
lots and lots of text here<br/>
lots and lots of text here<br/>
lots and lots of text here<br/>
lots and lots of text here<br/>
lots and lots of text here<br/>
<span id="some_bit">tooltip appears below-right f</span>
</div>
more surrounding text (should be overlapped by tooltip)
</div>
<div id="tooltip" style="width: 100px; height: 100px;">Whee</div>
CSS
#pane {
background-color: red;
}
#tooltip {
z-index: 9999;
display: none;
position: absolute;
background-color: yellow;
}
JavaScript
$('#somebit').hover(function() {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
// hovered element
var offset = $(this).offset();
var top = offset.top + docViewTop;
var left = offset.left;
var width = $(this).width();
var height = $(this).height();
var right = left + width;
var bottom = top + height;
// pane
var poffset = $('#pane').offset();
var ptop = poffset.top + docViewTop;
var pleft = poffset.left;
var pwidth = $('#pane').width();
var pheight = $('#pane').height();
var pright = pleft + pwidth;
var pbottom = ptop + pheight;
// tooltip
var ttop = bottom;
var tleft = right;
var twidth = $('#tooltip').width();
var theight = $('#tooltip').height();
var tright = tleft + twidth;
var tbottom = ttop + theight;
if (tright > pright)
tleft = pright - twidth;
if (tbottom > pbottom)
ttop = pbottom - theight;
if (tbottom > docViewBottom)
ttop = docViewBottom - theight;
$('#tooltip').offset({top: ttop, left: tleft});
$('#tooltip').css('display', 'block');
}, function() {
$('#tooltip').hide();
});