Update
I’ve just updated the jsFiddle so that you can see the “pop up” happening and how it’s never centered. It’s always 200px from top.
So if the user has scrolled down a long page and clicked to make the pop up happen, the pop up is back up at the top of the page – 200px instead of centered on the visible screen.
I’ll try out the answer below and update with results of that
I have a hidden div included in my layout as a partial
Here is the partial
A javascript function shows this div for showing the result of ajax requests
function showResultPopUpDiv(divId, title) {
var popUpId = document.getElementById(divId);
var popUpHeader = title;
var originalDivHTML;
var topPos = 200;
var popUpWidth;
var midPos;
var leftPos;
var spinnerOpts;
//Insert header text & open pop up
popUpId.style.display = "block";
document.getElementById("ajaxResultPopUpHeaderText").innerHTML = popUpHeader;
//Set position dimensions
popUpWidth = popUpId.offsetWidth / 2;
midPos = $(document).width() / 2;
leftPos = midPos - popUpWidth;
//Position pop up (center)
popUpId.style.top = topPos + "px";
popUpId.style.left = leftPos + "px";
//Insert spinning loader code here
... //left out for brevity
}
If a view is longer than a single screen and the user has scrolled to the bottom and clicked the submit button, this div pops up but cannot be seen unless the user scrolls back to the top.
How do I get this to center on the window correctly wherever the page is currently scrolled to.
This question and others that I’ve investigated have not solved this for me. Any ideas?
It sounds like what you want is a CSS position of “Fixed” (CSS Positioning 101). This will keep the object fixed relative to the viewport (the browser) rather than relative to the document. This will affect the way top and left behave.
Make sure you have something like:
To centre on the viewport you need to calculate positions relative to the viewport. The full JSFiddle (forked from your original, with added content for scrolling and styling to keep the button with you as you scroll) has all of the JavaScript, but since you’re working with jQuery then you just need to use
$(window)instead of$(document).$(document)happens to work okay for width, because the document is generally 100% of the width, but you should use$(window)anyway.