Preferred with jQuery, as it is much easier to understand.
The following works fine for horizontal. The problem is vertical, you can disable it from above, requiring the user to scroll up to see the pop-up window.
function pop_IT(X,event){ dist_to_right_edge = $('body').innerWidth()-(x-$.scrollbarWidth()); dist_to_bottom = $(window).height()-y; X=$('#'+X).get(0); X.style.left = 5+x+"px"; X.style.top = 5+y+"px"; if(dist_to_right_edge < (X.offsetWidth+5)){X.style.left = x - X.offsetWidth-5+"px";} if(dist_to_bottom < (X.offsetHeight+5)){X.style.top = y - X.offsetHeight-5+"px";} }
Then I load something like
$('#object').load('../whatever.php',function(event){pop_IT('object',event);});
source share