7 - A Sliding Challenge
Ok, this is the last of the java position moving things for a while but I just had to do this having been sort of challenged by my webbie-mate Dave who thought that the effect at www.panic.com/coda/ was quite nice.
I totally agree with him and so knocked this up just to prove a point. Ok there are a few problems: the graphics are rubbish, the sliding speed is constant and doesn't do that slow docking thing and yes, you can confuse it by clicking the controls too quickly but I leave fixing those minor issues as an exercise for the student.
Like the page at panic.com, this page has no fallback for when Javascript is not enabled but it's probably not too hard to put a script/noscript around the buttons that activate sliding to launch a separate page.
7 - A Sliding Challenge
How it works
Using some CSS, a div called "window" (the grey edged box) is a fixed size div that does not allow overflow. It contains "slider" (the multicoloured wide very wide div) that defaults to 0px offset inside "window". As it happens "slider" is made up of many sub-divs.
"Slider" with a negative offset showing its second area through "Window"
Clicking a link or button invokes some javascript code to change the x-offset of "slider" a bit at a time until it's reached the new value.
The javascript function increments the x-offest and then sets a timer to call itself in a short while to do the same all over again. When the offset is pretty close to the required value the function sets the offset to the exact value and doesn't bother calling itself again.
The CSS
div#window {width:500px; height:500px; border:2px solid #666; overflow:hidden;}
div #slider {margin-left:0px; width:2000px; height:500px;}
div.slideBox {float:left; width:500px; height:500px;}
div#Box1 { background-color:#F99; }
div#Box2 { background-color:#9F9; }
div#Box3 { background-color:#99F; }
div#Box4 { background-color:#999; }
The DIVs
<div id="window">
<div id="slider">
<div id="Box1" class="slideBox">
...content...
</div>
<div id="Box2" class="slideBox">
...content...
</div>
...etc...
</div>
</div>
The Code
var currPos=0 ;
var timerInterval = 2 ;
var timerPixels = 20 ;
function slideTo(divName,newPos)
{
// Calc new position
if (newPos>currPos)
currPos = currPos + timerPixels ;
else
currPos = currPos - timerPixels;
// Update the Div
div = document.getElementById(divName);
div.style.marginLeft = currPos + 'px' ;
// If there's a way to go...
if (Math.abs(newPos-currPos)>timerPixels)
{
// ... set timer to update increment
timerString = "slideTo('" + divName + "',"+newPos+")" ;
window.setTimeout (timerString,timerInterval);
}
else
// otherwise, finish off exactly.
div.style.marginLeft = newPos + 'px' ;
}
The links to show a new div call the above javascript with something like...
<a href="#" onClick="slideTo('slider',-500)">How it works</a>