diff --git a/parallax.js b/parallax.js index f8d08d7..341083f 100644 --- a/parallax.js +++ b/parallax.js @@ -9,28 +9,37 @@ var Parallax = { }); 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) || !$(this).attr('parallax-offset')) { return; } element = $(this); + //Calculate the center position of the image center_pos = (element.offset().top - $(window).scrollTop()) + (element.height() / 2); + // Calculate the position of the center point, relative to the center. perc = -(0.5 - ((window_top - center_pos) / window_bottom)); - + // Calculate the position of the center of the image from the percentage through the screen. pos = Math.round((perc * element.attr('parallax-offset')) * 100) / 100; + // 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' + 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(),