simple paralax effect on page [ 1145 views ]
Goal: simulate 3d effect on the page.
To to this we need minimum two layers. The foreground layer moving faster than the background. That’s all.
The foreground layer is the page itself. We need to create a slower background layer.
To do this we need a container DIV on the page. The size of this contanier is fit to the page size. Plus we need a second one DIV with the background image to create the effect.
<div id="backcont"><div id="backfly"></div></div>
and the style is
#backcont{ position: fixed; top: 0; left: 0; width: 100%; height: 100%; margin: 0; overflow: hidden; z-index: 0; } #backfly{ position:absolute; top:0; left:0; width:130%; height:130%; z-index: 0; background: url("/images/something.jpg"); }
This is the base. Let’s coding! First of all we need to know that the size height: 100%; width: 100%;
not enough because the page real size is not this. This is the screen size. We need to correct it later. Watch the code:
$(document).ready(function(){ var $backcont = $('#backcont'); var $backfly = $('#backfly'); function sizeCorrection(){ var hmax = $(document).height(); var wmax = $(document).width(); $backcont.height(hmax).width(wmax); $backfly.height(hmax*1.3).width(wmax*1.3); /* will be bigger than the page! */ }; sizeCorrection(); $(window).on('scroll resize', function(){ sizeCorrection(); var t = $(window).scrollTop(), l = $(window).scrollLeft(); $backfly.css({left:-l/10, top: -t/10}); }); });
In fact we have 3 layers.
1. the page itself
2. the slower moving (sluggish) background
3. fixed elements like the browser window
or other fixed elements if we have on the page (here is the sidebar for example)
The result is a 3d like view.