0

I have created a script to keep a div centred on the screen. It works fine in safari but for some reason jumps on window resize. I assume is is doubling the negative 'margin-top'. Anyone have any experience with this. I havent tried in chrome or ie.

// PART B
function cent() {
var $block = $("#block"),
    margintop = parseInt($block.height() / -2);
console.log('called');
$('#block').css("margin-top", margintop);
};

$(document).ready(function(){
cent();
});
$(window).resize(function(){
cent();
});

the site url: www.thebackroads.com.au

user2478466
  • 33
  • 1
  • 4

2 Answers2

1

If you log $block.height() You will see the javascript generated margin-top at load differs from the one when resizing because it seems your container actually has a different height.

This is probably due to the first cent() call being done when DOM isn't fully loaded. Or at least the text container hasn't reached it's final height because you show a preloader while image is being loaded. The reason for this is probably your external library. See DOM not fully loaded?

You can see this clearly in firebug your content is hidden when you calculate the height.

enter image description here

Read some solutions here:

jQuery: Get height of hidden element in jQuery

Community
  • 1
  • 1
Timmetje
  • 7,641
  • 18
  • 36
  • Do you think it might be calculating the height before the web-font loads? – user2478466 Jun 13 '13 at 07:42
  • Edit made, One thing for certain is you calculate when the content is hidden. See screenshot. – Timmetje Jun 13 '13 at 07:46
  • I think ive fixed it. Ive replaced `$(document).ready(function(){` with `$(window).bind("load", function(){` do you think this will cause any problems? – user2478466 Jun 13 '13 at 08:29
  • on second thoughts, this seems to have messed it up more. – user2478466 Jun 13 '13 at 08:34
  • best bet is to start calculating when your text is actually shown on screen. So do a method call when your image is loaded or whenever in the script your text shows. – Timmetje Jun 13 '13 at 08:38
0

Or try this script? Calculate with window's height.

function cent() {
    var margintop = ($(window).height() - $('#block').height()) / 2;
    $('#block').css("margin-top", margintop);
};
yeyene
  • 7,297
  • 1
  • 21
  • 29