Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

offsetHeight and offsetWidth calculating incorrectly on first onclick event, not second

I have written the following script to display a hidden element, then fix it's position to the center of the page.

function popUp(id,type) {
var popUpBox = document.getElementById(id);

popUpBox.style.position = "fixed";
popUpBox.style.display = "block";

popUpBox.style.zIndex = "6";

popUpBox.style.top = "50%";
popUpBox.style.left = "50%";

var height = popUpBox.offsetHeight;
var width = popUpBox.offsetWidth;
var marginTop = (height / 2) * -1;
var marginLeft = (width / 2) * -1;

popUpBox.style.marginTop = marginTop + "px";
popUpBox.style.marginLeft = marginLeft + "px";
}

When this function is called by an onclick event, the offsetHeight and offsetWidth are calculated incorrectly, thus not centering the element correctly. If I click the onclick element a second time, the offsetHeight and offsetWidth calculate correctly.

I have tried changing the order in every way I can imagine, and this is driving me crazy! Any help is very much appreciated!

like image 465
saoyr5 Avatar asked Sep 13 '11 15:09

saoyr5


1 Answers

I am guessing your height and width are not defined on the parent. See this fiddle where it works fine. Boy I'm smart. http://jsfiddle.net/mrtsherman/SdTEf/1/

Old Answer I think this can be done a lot more simply. You are setting the top and left properties to 50%. This will place the fixed element slight off from the center. I think you are then trying to pull it back into the correct position using negative margins. Instead - just calculate the correct top/left values from the start and don't worry about margin. Here is a jQuery solution, but it can be easily adapted to plain js. I also think your current code won't work if the window has been scrolled at all.

//this code will center the following element on the screen
$('#elementid').click(function() {
    $(this).css('position','fixed');
    $(this).css('top', (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop() + 'px');
    $(this).css('left', (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft() + 'px');
});
like image 113
mrtsherman Avatar answered Oct 18 '22 09:10

mrtsherman