Skip to content

Instantly share code, notes, and snippets.

@alexJunger
Created September 16, 2014 22:44
Show Gist options
  • Select an option

  • Save alexJunger/e45bc77a6003d66237e5 to your computer and use it in GitHub Desktop.

Select an option

Save alexJunger/e45bc77a6003d66237e5 to your computer and use it in GitHub Desktop.
jquery.parallax
/*************************
*---JQUERY PARALLAX---- *
*************************
*
* Alexander Junger, 2014
* License: MIT
*
*/
(function($) {
'use strict';
var DEFAULT_CONFIG = {
minWidth: 780
};
var $window = $(window),
$body = $('body'),
$document = $(document);
var elements = [];
window.elements = elements;
var Parallax = function($el, config) {
if(!$el.length) {
return;
}
this.$el = $el;
this.c = $.merge(config, {minOff: 0, maxOff: $document.height(), speed: 0.1});
this.speed = parseFloat(this.c.speed);
this.originalOffset = parseInt(this.$el.css('top'), 10);
elements.push(this);
};
Parallax.prototype.update = function() {
if(this.isVisible()) {
this.$el.css('top', this.getOffset.bind(this));
}
};
Parallax.prototype.isVisible = function() {
var docTop = $window.scrollTop();
var docBottom = docTop + $window.height();
var elemTop = this.$el.offset().top;
var elemBottom = elemTop + this.$el.height();
return ((elemBottom >= docTop) && (elemTop - 400 <= docBottom));
};
Parallax.prototype.getOffset = function() {
var rawOffset = this.originalOffset - $window.scrollTop() * this.speed * 0.05;
return Math.max(0, Math.min(rawOffset));
};
var updateAll = function() {
$body.css({
'background-position': 'center -' + $window.scrollTop() * 0.15 + 'px'
});
elements.forEach(function(p) {
p.update();
});
};
$window.on('scroll', updateAll);
$.fn.parallax = function() {
if($window.width() <= DEFAULT_CONFIG.minWidth) {
return false;
}
this.each(function() {
$(this).data('parallaxObject', new Parallax($(this), {
speed: parseFloat($(this).data('parallax-speed'))
}));
});
return this;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment