Skip to content

Instantly share code, notes, and snippets.

@optikalefx
Last active December 17, 2015 23:28
Show Gist options
  • Save optikalefx/5688919 to your computer and use it in GitHub Desktop.
Save optikalefx/5688919 to your computer and use it in GitHub Desktop.
function ParallaxItem(containerNode) {
var container, bgElements, offset, bgHeight, containerHeight, maxScrolls, height;
container = Y.one(containerNode);
bgElements = container.all('.parallax-background');
function refreshCoords() {
offset = container.getY();
containerHeight = container.get('offsetHeight');
bgHeights = [];
maxScrolls = [];
bgElements.each(function(item) {
height = item.get('offsetHeight');
bgHeights.push(height);
maxScrolls.push(containerHeight - height + 2);
});
}
function refresh(docScrollY) {
var i, j, scroll, transformParam;
i = 0;
bgElements.each(function(bgElement) {
scroll = -Math.round(((docScrollY - offset) / containerHeight) * maxScrolls[i]);
scroll = Math.max(scroll, maxScrolls[i]);
var transformParam;
if (!use2DTransform) {
transformParam = 'translate3d(0px,' + scroll + 'px, 0px)';
} else {
transformParam = 'translateY(' + scroll + 'px)';
}
if (transform && transformParam) {
bgElement.setStyle(transform, transformParam);
bgElement.setStyle(prefixes.w3c, transformParam);
} else {
bgElement.setStyle('marginTop', scroll + 'px');
}
i++;
});
}
refreshCoords();
return {
'refresh': refresh,
'refreshCoords': refreshCoords
}
}
function refreshParallaxItems() {
var docScrollY = Y.DOM.docScrollY();
if (!parallaxItems || !parallaxItems.length) {
return false;
}
for (var i = 0, j = parallaxItems.length; i < j; i++) {
parallaxItems[i].refresh(docScrollY);
}
}
function scrollWatcher() {
if (requestAnimationFrame) {
requestAnimationFrame(refreshParallaxItems);
} else {
refreshParallaxItems();
}
}
function addParallaxItem(containerNode) {
parallaxItems.push(new ParallaxItem(containerNode));
if (!scrollHandler) {
scrollHandler = Y.on('scroll', scrollWatcher);
}
}
if (useParallax) {
nodes = Y.all('#flickr-frames .parallax-item');
nodes.each(function(item) {
addParallaxItem(item);
});
Y.on('PhotoListView:render', function() {
var now = new Date();
if (now - lastExec > 250) {
for (var i = 0, j = parallaxItems.length; i < j; i++) {
parallaxItems[i].refreshCoords();
}
lastExec = now;
}
});
refreshParallaxItems();
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment