I’m trying to center a div, here is what i came up so far:
function miniWindow(content) {
$('#miniWindow').hide();
$('#miniWindow').css({'top' : '280px', 'left' : '385px'}); //start position
$('#miniContent').html(content); //<-- the problem line
//center the div
setTimeout( function() {
var width = $('#miniWindow').outerWidth();
var height = $('#miniWindow').outerHeight();
$('#miniWindow').css({'left' : '-='+width/2, 'top' : '-='+height/2});
$('#miniWindow').show();
}, 1000);
}
miniWindow('fubar'); //invoke
The problem is that I need a timeout to give the .html() function time to set width and height although .html() should be synchronous!?
Is there any other solution without using timeout to solve this problem?
outerHeight() and innerHeight() don’t work on hidden elements.
Try calling
$('#miniWindow').show()before setting the position (and getting the width/height).