Forum Moderators: open

Message Too Old, No Replies

center element based on viewing area

         

d40sithui

7:11 pm on Jan 9, 2008 (gmt 0)

10+ Year Member



Hello,
I have an absolute 100px by 100px div that contains the "now loading.." message thats activated via AJAX. The div currently is centered on the page. if the page were to be scrolled down far enough, the element would eventually disapear since i'm cutting off the display area. my question then is, how would you get the div to display always to the center, not based on the page, but based on the screen or the viewing area?

RonPK

9:27 am on Jan 10, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



scrollTop
is your friend, as it tells you how far down the user has scrolled. Here's a bit of code that might get you going:

function putInCenter() { 
var d = document;
var rootElm = (d.documentElement && d.compatMode == 'CSS1Compat') ? d.documentElement : d.body;
var vpw = self.innerWidth ? self.innerWidth : rootElm.clientWidth; // viewport width
var vph = self.innerHeight ? self.innerHeight : rootElm.clientHeight; // viewport height
var myDiv = d.getElementById('divIDhere');
myDiv.style.position = 'absolute';
myDiv.style.left = ((vpw - 100) / 2) + 'px';
myDiv.style.top = (rootElm.scrollTop + (vph - 100)/2 ) + 'px';
}

The first few lines should deal with compat/quirks modes and browser differences. After that, all that needs to be done is to position the div.

If you need the div to stay where it is while scrolling, use position = fixed (won't work in IE6).

d40sithui

5:52 pm on Jan 10, 2008 (gmt 0)

10+ Year Member



thanks Ron,
I got it working. You're the greatest

-khanh