Skip to content

Instantly share code, notes, and snippets.

@vespoli
Last active January 4, 2016 02:28
Show Gist options
  • Save vespoli/8554759 to your computer and use it in GitHub Desktop.
Save vespoli/8554759 to your computer and use it in GitHub Desktop.
Light weight parallax that uses images not background images and just what I needed. WIll post markup and css later. Needs cleanup too. Expects element to be passed containing the image used as the background. kind of specific for now.
(function ($) {
var $window = $(window);
var windowHeight = $window.height();
var Parallax = function (element, options) {
var $this = $(element);
var $img = $this.find('img:first');
var obj = this;
var thisTop, maxOffset, thisHeight;
var settings = $.extend({
heightOffset: function(){return 0;}, //can be used to offset theheight of the element
speed: 1 //max movement with image size and viewport
}, options || {});
//TODO: pull this out maybe?
//dont want this in measure because im not updating for window resizing
//too expensive, not that important
$this.css({'height':windowHeight-settings.heightOffset()+'px'});
var measure = function () {
windowHeight = $window.height();
thisTop = $this.offset().top;
maxOffset = $img.height()-$this.height(); //pixels extra to work with from the image
thisHeight = $this.height();
//top = $this.offset().top;
};
var update = function () {
var pos = $window.scrollTop();
// Can we see it?
if (thisTop + thisHeight < pos || thisTop > pos + windowHeight) {
return;
}
// How much can we see?
// how much have we shown divided by the element + window height
// tells us what percent we have scrolled through the item. 100% is off screen, scrolled past
var ratio = (pos+windowHeight-thisTop) / (thisHeight+windowHeight);
//take the max numbers of pixels we have to work with and figure out how much to pull off screen
var offset = -(Math.round(ratio*maxOffset));
$img.css('top', offset + "px");
};
//TODO: section seems poopy...
$window.on('scroll', function(){ //just update
update();
}).on('resize',function(){ //recalculate
measure();
update();
});
measure();
update();
};
$.fn.parallax = function (options) {
return this.each(function () {
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('parallax')) {return;}
// pass options to plugin constructor
var parallax = new Parallax(this, options);
// Store plugin object in this element's data
element.data('parallax', parallax);
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment