Strafe

JavaScript, I have often felt, is an inelegant hack that is a blight on the internet, and that only the pure and and untainted HTML/CSS websites are worthy. That programming languages can elicit the same partisan bigotry as spoken ones, and that social Darwinism can exist in the lonely isolation of the computer programmer, is hilarious.

So to combat my prejudice I opted to visit this strange world JavaScrpit, and following the helpful criticism of my home boy Az (check out his sweet website Blemished Napkins) I created a script to scroll the website horizontally.

The logic is straight forward. There is a pair of fixed arrows that scroll a page width on click. So the first thing to do is to find the window width, and the window position. Cross browser compatibility can be achieved using the following functions (adapted from here):

function windowWidth() {
    var myWidth = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
    myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth ) {
        myWidth = document.documentElement.clientWidth;
    } else if( document.body && document.body.clientWidth ) {
        myWidth = document.body.clientWidth;
    }
    return myWidth;
}

function windowPosition() {
    var scrOfX = 0
    if( typeof( window.pageXOffset ) == 'number' ) {
        scrOfX = window.pageXOffset;
    } else if( document.body && document.body.scrollLeft ) {
        scrOfX = document.body.scrollLeft;
    } else if( document.documentElement && document.documentElement.scrollLeft ) {
        scrOfX = document.documentElement.scrollLeft;
    }
    return scrOfX;
}

Next, the scrolling method. To do this smoothly, setting the window view to the pixel one window width away is insufficient. Instead, it has to be reduced into many small chunks that occur in rapid succession, to give the illusion of a continuous movement. The wrapper function pageScrollRight calculates the 'destination' pixel on the X axis, and calls the recursive function goRight to iterate through scrolling increments until the destination is reached:

var delay = 5;
var scrollOffset = 25;

function goRight(targetXPos,lastPosition) {
    var x = windowPosition()+100;
    if(lastPosition == x) return false;
    if (xtargetXPos){
        window.scrollBy(-scrollOffset, 0);
        timer = setTimeout('goLeft('+targetXPos+','+x+')', delay);
    }
    else clearTimeout(timer);
    return false;
}

function pageScrollRight() {
    var moveRight = windowPosition() + windowWidth();
	goRight(moveRight,-1);

}

function pageScrollLeft() {
    var moveLeft = windowPosition() - windowWidth();
    goLeft(moveLeft,-1);
}

Then to use it in the html:

<a href="javascript:pageScrollRight();">Scroll Right</a>

Still to add - acceleration and deceleration, and mouse wheel scrolling.

Typing and design by Gib Hemani

2011-01-02 22:31:41