Tuesday, August 3rd, 2010
I was recently working on a project that required me to write my own JavaScript (without the use jQuery awesomeness). One of the main specifications was a lightbox-style popup that centred on the page.
Normally this would be nice and simple to align a box in jQuery, by getting the height and width of the window and dividing by two, like so:
var x = win.scrollLeft();
var y = win.scrollTop();
var h = win.height();
var w = win.width();
var con = $( '#mybox' );
con.css({
left : ( x + ( w / 2 ) - ( con.width() / 2 ) ) + 'px',
top : ( y + ( h / 2 ) - ( con.height() / 2 ) ) + 'px'
});
Nice and simple yeah? Well, that’s what I thought when I took on the challenge of creating the script myself. Basically, I used my cunning and came up with this:
var w = ( !isIE ? window.innerWidth : document.documentElement.clientWidth );
var x = ( !isIE ? window.scrollX : document.documentElement.scrollLeft );
var y = ( !isIE ? window.scrollY : document.documentElement.scrollTop );
var con = document.getElementById( 'mybox' );
con.style.left = ( x + ( w / 2 ) - ( con.offsetWidth / 2 ) ) + 'px';
con.style.top = ( y + ( h / 2 ) - ( con.offsetHeight / 2 ) ) + 'px';
So again, pretty standard. I was using IE’s retarded document.documentElement property and I thought that was it. But oh no.
It turns out that IE has different properties depending on the doctype set in the HTML. So, for example, if the doctype is XHTML 1.0 Strict, then the above code works. However, if it is XHTML 1.0 Transitional, then it doesn’t. Super fun.
So rather than sticking around to see how many different variations IE wants to mess around with, I create a sort of fail-proof script:
var w = ( !isIE ? window.innerWidth : document.documentElement.clientWidth );
var x = ( !isIE ? window.scrollX : document.documentElement.scrollLeft );
var y = ( !isIE ? window.scrollY : document.documentElement.scrollTop );
if ( isIE )
{
h = ( h == 0 ? document.documentElement.scrollHeight : h );
w = ( w == 0 ? document.documentElement.scrollWidth : w );
h = ( h == 0 ? document.body.scrollHeight : h );
w = ( w == 0 ? document.body.scrollWidth : w );
x = ( x == 0 ? document.body.scrollLeft : x );
y = ( x == 0 ? document.body.scrollTop : y );
}
var con = document.getElementById( 'mybox' );
con.style.left = ( x + ( w / 2 ) - ( con.offsetWidth / 2 ) ) + 'px';
con.style.top = ( y + ( h / 2 ) - ( con.offsetHeight / 2 ) ) + 'px';
Essentially it checks, twice, if the height and width of the window are there. So far it hasn’t failed for me, and if you’re ever in the situation when you need to write a bit of JavaScript without using a library, let me know if this helped you at all or if you can improve it!