Home > Programming > Centering the scrollbar horizontally using javascript

Centering the scrollbar horizontally using javascript

So normally when we develop a website template we make it liquid layout to fit in most browsers however in some cases we want the minimum width to be set with an optional overflow image. Kind of hard to picture… at any rate we wanted the browser to scroll horizontally but be centered on the page in lower resolutions without having to mess with the template.

I did a lot of searching and even found some people saying it was not possible. Well I tell you it is. Here is a script that will work for you. Just copy to your own autoscroll.js file and include it, or you can copy paste this into a script block.

function setScroll()
{
var docWidth;
var docMinWidth = 1182;  //min width in pixels any browser size smaller then this will cause the scrollbar to appear and center

docWidth = getDocWidth();


if( typeof( window.pageYOffset ) == ‘number’ ) {
//Netscape compliant
scrOfY = window.pageYOffset;
scrOfX = window.pageXOffset;
if (docWidth <
docMinWidth ) { window.scroll((docMinWidth - docWidth) / 2, scrOfY);}
} else if( document.body && ( document.body.scrollLeft != ‘undefined’ || document.body.scrollTop != ‘undefined’ ) ) {
//DOM compliant
scrOfY = document.body.scrollTop;
scrOfX = document.body.scrollLeft;
if (docWidth <
docMinWidth ) { window.scroll((docMinWidth - docWidth) / 2, scrOfY);}
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
//IE6 standards compliant mode
scrOfY = document.documentElement.scrollTop;
scrOfX = document.documentElement.scrollLeft;
if (docWidth <
docMinWidth ) { window.scroll((docMinWidth - docWidth) / 2, scrOfY);}
}

}

function getDocWidth()
{
if (document.body.scrollWidth)
return document.body.scrollWidth;
var w = document.documentElement.offsetWidth;
if (window.scrollMaxX)
w += window.scrollMaxX;
return w;
}

function addOnloadEvent(fnc){
if ( typeof window.addEventListener != “undefined” )
window.addEventListener( “load”, fnc, false );
else if ( typeof window.attachEvent != “undefined” ) {
window.attachEvent( “onload”, fnc );
}
else {
if ( window.onload != null ) {
var oldOnload = window.onload;
window.onload = function ( e ) {
oldOnload( e );
window[fnc]();
};
}
else
window.onload = fnc;
}
}

addOnloadEvent(setScroll);


Categories: Programming
  1. Ben
    August 17, 2009 at 1:21 am | #1

    Hi,

    I was looking for this script since a long time. Good job!

    I’ve got an error on that line
    if( typeof( window.pageYOffset ) == ‘number’ ) {

    Any idea?
    Thanks!

  2. August 17, 2009 at 5:58 am | #2

    What is the error message you receive?

  1. No trackbacks yet.