I had the same problem on one of my pages and solved it with this code:
function showTooltip(x, y, contents) {
var params = {
position: 'absolute',
display: 'none',
border: '2px solid #333333',
'border-radius': '3px',
padding: '3px',
size: '10',
'background-color': 'lightyellow',
opacity: 0.90
};
if (x < 0.8 * $(window).width()) {
params.left = x + 20;
}
else {
params.right = $(window).width() - x + 20;
}
if (y < 0.8 * $(window).height()) {
params.top = y + 5;
}
else {
params.bottom = $(window).height() - y + 10;
}
$('<div id="tooltip">' + contents + '</div>').css(params).appendTo('body').fadeIn(200);
}
Here I compare the x
and y
position values to the window size and position the tooltip to the left of the mouse position if the mouse position is near the right border and above the mouse position if it is near the bottom.