The Objective:
I’m attempting to create a modal dialog that pops up at the event.clientX/Y coordinates of a click event, but which corner of the dialog box sits at the x,y position depends on which view port quadrant the event is in.
The positioning scheme is simple. The dialog box’ top/bottom edge should be positioned at the event.clientY coordinate depending on whether .clientY is in the upper/lower half of the view port. The box’ left/right edge should be at the.clientX coordinate depending on whether .clientX is in the left/right half of the view port. Thus, if the event is in the upper left quadrant, the dialog’s upper left corner will sit at .clientX/Y, if in the lower right quadrant, then its lower right corner will sit at x,y, etc.
The Problem:
I have the solution to positioning the dialog on the x-axis but the solution to positioning it on the y-axis is proving elusive. The problem is that the correct corner sometimes sits at x,y and sometimes is offset up or down from x,y. The discrepancy seems to be proportional to the amount the page has been scrolled. As the page is scrolled up, the discrepancy grows larger. The problem is intractable for me.
Illustrations:
There is a pen, Popup Project, on CodePen. The positioning function begins on JS line 233. There are three screenshots, screenshot 0, screenshot 1, and screenshot 2 illustrating the problem. The dialog’s behavior can be seen on the /test-table page of my website, but also on the pen and, if tested locally, there.
The Code:
The function I’m using is:
// positon popup on page relative to cursor
// position at time of click event
function positionPopupOnPage( evt ) {
var vpWH = []; // viewport Width-Height
var vpW, vpH;
var coordX = evt.clientX;
var coordY = evt.clientY;
vpWH = getViewPortWidthHeight();
vpW = vpWH[0];
vpH = vpWH[1];
popup.style.visibility = 'hidden';
popup.style.position = 'absolute';
// if not display: block, .offsetWidth & .offsetHeight === 0
popup.style.display = 'block';
popup.style.zIndex = '10100';
if ( coordX > vpW/2 ) { coordX -= popup.offsetWidth; }
if ( coordY > vpH/2 ) { coordY -= popup.offsetHeight; }
popup.style.top = coordY + 'px';
popup.style.left = coordX + 'px';
popup.style.visibility = 'visible';
} // end fn positionPopupOnPage
Mille Grazie
Any help will be greatly appreciated. Thank you for your interest in my question and for your time.
-Steve