views:

384

answers:

2

Hi!

Can anyone tell me where I am going wrong... I am using the following to vertically align a div by setting the margin-top, using the (window).height. 625 is the height of the Div being centered...

This works in Firefox but IE7 doesn't set the margin-top until you resize the browser window.

The test site is at http://guylloyd.co.uk

Any thought would be amazingly appreciated!

Martin

jQuery.noConflict();
jQuery(document).ready(function () {

jQuery(function(){   
var $marginTop = ((jQuery(window).height() - 625) / 2 + 'px');
if(jQuery(window).height() > 625){
jQuery('body').css({'margin-top': $marginTop});   
}
});

jQuery(window).resize(function(){
var $marginTop = ((jQuery(window).height() - 625) / 2 + 'px');
if(jQuery(window).height() > 625){
jQuery('body').css({'margin-top': $marginTop});
}
});

});

A: 

I'm not sure about your actual question, which is why IE7 isn't setting the margin until you resize the window, but you might consider reducing redundant code like this:

function doResize() {
    var $marginTop = ((jQuery(window).height() - 625) / 2 + 'px');
    if(jQuery(window).height() > 625){
        jQuery('body').css({'margin-top': $marginTop});
    }
}

jQuery.noConflict();
jQuery(document).ready(doResize);
jQuery(window).resize(doResize);

As for IE, what happens if you add some alert statements to the method so you can tell when they are called. Is IE7 not executing the document.ready function? Or is it executing, but not doing anything?

Seth Petry-Johnson
Thanks Seth - i am just learning jQuery so it's great to see how i can tidy up my code.. I have used CSS to resolve the issue - adding an extra div but i'll pretend i've not seen it...Martin
Martin
A: 

You really dont need to use jquery to lay out the content in that fashion, simple css and xhtml could achieve the same thing.

It could be an issue the same as in IE6 which causes a delay in the javascript to be executed try including a time out and a call to the code Seth has designed

function doResize() {   
    var $marginTop = ((jQuery(window).height() - 625) / 2 + 'px');   
    if(jQuery(window).height() > 625){   
        jQuery('body').css({'margin-top': $marginTop});   
    }   
}  
//when document has been fully loaded
jQuery(document).ready(function()
{
    setTimeout('doResize()', 1 );

}); 
Mauro
Hey thanks Mauro - you're absolutely right... CSS is the best answer - By inserting another DIV before the content and setting its height at 50% and margin-bottom as half the height of my content - works perfectly. Just a shame about adding a new div - i guess i could, and should, do that with jQuery... But that's another day!body {position:absolute; height:100%; width:100%;}#verticalAlign {height:50%; margin-bottom:-312px;}Thanks again!M.
Martin