archive
/
simparallax
Archived
1
Fork 0
This repository has been archived on 2023-03-26. You can view files and clone it, but cannot push or open issues or pull requests.
simparallax/parallax.js

41 lines
1.5 KiB
JavaScript
Raw Normal View History

2015-08-13 13:43:42 +01:00
var Parallax = {
2015-08-13 14:04:18 +01:00
initialise: function(createEvents) {
$(this.ident).each(function(){
// Calculate Offset
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();}
this.calculate();
2015-08-13 13:43:42 +01:00
},
calculate: function() {
2015-08-13 14:04:18 +01:00
window_top = $(window).scrollTop();
window_bottom = window_top + $(window).height();
$(this.ident).each(function(){
2015-08-13 14:47:50 +01:00
if (!is_on_screen(this) || !$(this).attr('parallax-offset')) { return; }
2015-08-13 14:04:18 +01:00
element = $(this);
center_pos = (element.offset().top - $(window).scrollTop()) + (element.height() / 2);
perc = -(0.5 - ((window_top - center_pos) / window_bottom));
2015-08-13 13:43:42 +01:00
2015-08-13 14:04:18 +01:00
pos = Math.round((perc * element.attr('parallax-offset')) * 100) / 100;
element.css('background-position',"0px " + pos + "px");
});
2015-08-13 13:43:42 +01:00
},
2015-08-13 14:04:18 +01:00
createEvents: function() {
$(window).scroll(function() { Parallax.calculate(); });
2015-08-13 14:10:00 +01:00
$(window).resize(function() { Parallax.initialise(false); })
2015-08-13 13:43:42 +01:00
},
2015-08-13 13:44:14 +01:00
ident: '.parallax'
2015-08-13 13:43:42 +01:00
}
function is_on_screen(elm) {
2015-08-13 14:04:18 +01:00
var vpH = $(window).height(),
st = $(window).scrollTop(),
2015-08-13 13:43:42 +01:00
y = $(elm).offset().top,
elementHeight = $(elm).height();
return ((y < (vpH + st)) && (y > (st - elementHeight)));
}