Skip to content

Instantly share code, notes, and snippets.

@cers
Created March 22, 2012 19:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save cers/2161848 to your computer and use it in GitHub Desktop.
Save cers/2161848 to your computer and use it in GitHub Desktop.
Scrolling along the Z-Axis
<html>
<head>
<title>Scrolling along the Z-Axis</title>
<!--
Example from http://eng.wealtfront.com
Assumes browser window is sized at a height of 400px (the size of the black box).
-->
<style>
body{height:600px;}
#viewport {
position:fixed;
-moz-perspective:100px;
-moz-perspective-origin:50% 50%;
border: 2px solid black;
height: 400px;
width: 400px;
left:50%;
margin-left:-200px;
}
.box {
position:absolute;
width:100px;
height:100px;
left:50%;
top:50%;
margin-left:-50px;
margin-top:-50px;
}
#a {
background-color:rgba(255,0,0,.5);
border:2px solid red;
-moz-transform:translateZ(-100px)
}
#b {
background-color:rgba(0,255,0,.5);
border:2px solid green;
-moz-transform:translateZ(-50px)
}
#c {
background-color:rgba(0,0,255,.5);
border:2px solid blue;
-moz-transform:translateZ(0px)
}
</style>
</head>
<body>
<div id="viewport">
<div class="box" id="a"></div>
<div class="box" id="b"></div>
<div class="box" id="c"></div>
</div>
<script>
var scrollPosition = document.body.scrollTop,
boxPositions = [-100, -50, 0];
function scrollDelta() {
var newScrollPosition = document.body.scrollTop,
delta = newScrollPosition - scrollPosition;
scrollPosition = document.body.scrollTop;
return delta;
}
function moveCamera() {
var boxes = document.getElementsByClassName("box"),
delta = scrollDelta();
for (var i=0,l=boxes.length;i<l;i++) {
boxPositions[i] += parseInt(delta);
boxes[i].style.MozTransform = "translateZ("+boxPositions[i]+"px)";
}
}
window.addEventListener("scroll", moveCamera, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment