3D Javascript Effect
Posted on
Here’s a little Javascript effect that will give your site a subtle 3D look by simulating a parallax between the content of your site and the background. Try out the effect now by scrolling up and down on my site. CSS only gives us two choices for background-attachment: scroll (default) and fixed. This script is sort of halfway between the two by making the background scroll half as fast as the content.
$(function(){
$("body").css("backgroundAttachment", "fixed");
$(window).scroll(function () {
$("body").css("backgroundPosition", '50% '+(0-$(window).scrollTop()/2)+'px');
});
});
The second line, $("body").css("backgroundAttachment", "fixed");, is optional. You could set
the background to fixed in CSS, but I prefer to do it this way so that if Javascript is disabled, the background
will default to scroll.
This script also assumes the background is centered. If it’s left aligned, change the 50%
to 0 px.
I’ve tested this in Firefox, IE and Chrome. It works in all three, but staggers a bit in Firefox.