Accepted answer

Here I made a copy of your CodePen

It works more or less the way you wanted.

The principle is quite simple. If the popover is about to be out of a viewport you change its position so that it is inside a viewport.

if (xPos > maxRight) {
    xPos = maxRight;
if (yPos > maxDown) {
    yPos = maxDown;

Related Query

More Query from same tag