OffsetHeight and offsetWidth are not calculated correctly on the first onclick event, and not in seconds

I wrote the following script to display a hidden element, and then fixed it in the center in 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 the onclick event, offsetHeight and offsetWidth are not calculated correctly, therefore, they do not center the element correctly. If I clicked the onclick element a second time, the offset Height and offsetWidth will be correctly calculated.

I tried to change the order in every way, I can imagine, and it drives me crazy! Any help is much appreciated!

+6
source share
1 answer

I assume that your height and width are not defined for the parent. Look at this fiddle where it works fine. Boy, I'm smart. http://jsfiddle.net/mrtsherman/SdTEf/1/

Old answer. I think it can be done much easier. You set the top and left properties to 50%. This will cause the fixed element to be slightly off-center. I think that you are trying to return it to the correct position using negative fields. Instead, simply calculate the correct top / left values ​​from the start and don't worry about margin. Here is a jQuery solution, but it easily adapts to simple js. I also think that your current code will not work if the window scrolls 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'); }); 
+1
source

Source: https://habr.com/ru/post/897242/


All Articles