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

10,768

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');
});
Share:
10,768
saoyr5
Author by

saoyr5

Updated on June 22, 2022

Comments

  • saoyr5
    saoyr5 about 2 years

    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!

  • saoyr5
    saoyr5 almost 13 years
    You are correct, you're way will work (I tested it to make sure offsetHeight and offsetWidth were correct), except that you cannot resize the window and have the div stay perfectly centered, which is something I am looking for. I am really most interested in why my offsetHeight and offsetWidth are not giving me the correct numbers, as I use this css technique all the time and it always gives me the desired effect.
  • mrtsherman
    mrtsherman almost 13 years
    Ahh, I see now. I upvoted your question so hopefully someone gets you a better answer. You could bind the above to the $(window).resize() event, but your method is certainly more elegant.