How to Position Custom Tooltip within Visible Window

Hello,

I am using the first example at Tooltip | Dash for Python Documentation | Plotly for custom tooltip. In that example, the tooltip for the top few points goes out of the chart space (and may become invisible depending upon the space around the chart).

On the same page, another example adds direction to tooltip to move tooltip between top and bottom (based on y).

Is there a way to automatically move tooltip to visible area if it goes outside of the chart space?

Thanks.