I had a problem where I am position a popup <div> in the center of the window using:
var popup = $("#popup"), popupWidth = popup.css("width").replace("px",""), popupHeight = popup.css("height").replace("px","");
var xPosition = ($(window).width() - popupWidth) / 2;
var yPosition = (($(window).height() - popupHeight) / 2) + $(window).scrollTop();
if (yPosition <= 0){
yPosition = '0';
} else if(yPosition <= $(window).scrollTop()){
yPosition = $(window).scrollTop();
} else {
yPosition = yPosition - 68; //minus top shaddow height
}
if (xPosition >= $('body').offset().left) {
xPosition = xPosition;
} else {
xPosition = '0';
}
$(popup).css({
'top': yPosition + 'px',
'left': xPosition + 'px',
'display' : 'block',
'height' : 'auto'
}).addClass("popup-open");
The problem I had was that on first load the height of the popup was being returned as 0 because it is hidden until after the position above has been worked out. To resolve this I set a default height via CSS and then once the popup has been displayed I overwrite this to auto.
The problem now is that if the popup has been closed and re-opened the height is auto. Is there a way to find the CSS height:value in the stylesheet not the inline height:auto
Updated Code
Following Nicola answer here is the fixed code:
var popup = $("#popup"), popupWidth = popup.css("width").replace("px",""), popupHeight = popup.css("height").replace("px","");
// Save/Get original height
if(popupHeight == "auto"){
popupHeight = popup.data('origHeight');
} else {
popup.data('origHeight', popupHeight);
}
var xPosition = ($(window).width() - popupWidth) / 2;
var yPosition = (($(window).height() - popupHeight) / 2) + $(window).scrollTop();
Why don’t you save the original values in a variable?
When you reopen the pop up you use the original values instead of the actual values
Or you could use use data() to store it and retrieve it