var Parallax = { initialise: function(createEvents) { $(this.ident).each(function(){ // Calculate Offset if ($(this).attr('parallax-inset') && $(this).attr('parallax-mode') == 'inset') { inset = $(this).attr('parallax-inset'); image_height = $(this).height(); range = image_height / inset; $(this).attr('parallax-offset', range / 2); } }); console.log("Parallax Initialised."); if (createEvents) {this.createEvents();} //Calculate the initial positions of the images. this.calculate(); }, calculate: function() { // Get the window dimentions. window_top = $(window).scrollTop(); window_bottom = window_top + $(window).height(); $(this.ident).each(function(){ // If the element isn't on the screen, or wasn't initialised, ignore it. if (!is_on_screen(this)) { return; } element = $(this); //Calculate the center position of the image center_pos = (element.offset().top - window_top) + (element.height() / 2); // Calculate the position of the center point, relative to the center. perc = -(0.5 - ((window_top - center_pos) / window_bottom)); switch(element.attr('parallax-mode')) { case 'inset': pos = Math.round((perc * element.attr('parallax-offset')) * 100) / 100; console.log(pos) break; case 'linear': default: pos = perc*(element.height()/2); break; } // Apply the calculated value. element.css('background-position',"0px " + pos + "px"); }); }, createEvents: function() { // Create scroll and resize events for Parallax $(window).scroll(function() { Parallax.calculate(); }); $(window).resize(function() { Parallax.initialise(false); }) }, ident: '.parallax' //The identifier for Parallax elements } // Check if the element is on the screen, not necessarily all of it. function is_on_screen(elm) { var vpH = $(window).height(), st = $(window).scrollTop(), y = $(elm).offset().top, elementHeight = $(elm).height(); return ((y < (vpH + st)) && (y > (st - elementHeight))); }