Skip to content

Instantly share code, notes, and snippets.

@Prozi
Created August 18, 2016 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Prozi/439efb21a705a4bd93cccc3502037c10 to your computer and use it in GitHub Desktop.
Save Prozi/439efb21a705a4bd93cccc3502037c10 to your computer and use it in GitHub Desktop.
angular1 parallax scroll directive
'use strict';
export default angular.module('myApp')
.directive('ngParallax', [
'myStorage',
(myStorage) => ({
restrict: 'AE',
scope: {
pattern: '=',
reverse: '=',
speed: '=',
opacity: '='
},
link: ($scope, elem, attr) => {
const container = elem[0];
const img = new Image();
img.addEventListener('load', onImageLoad, false);
img.src = $scope.pattern;
container.insertBefore(img, container.firstChild);
function onUpdate () {
let top = container.getBoundingClientRect().top;
let imgHeight = img.height;
let containerHeight = parseInt((container.style.height || '380px').replace('px', ''), 10);
let bottom = container.getBoundingClientRect().top + containerHeight;
let parallaxDist = imgHeight - containerHeight;
let windowHeight = myStorage.window.height;
let windowBottom = myStorage.window.top + windowHeight;
let percentScrolled = (windowBottom - top) / (containerHeight + windowHeight);
let parallax = Math.round(parallaxDist * percentScrolled * parseFloat($scope.speed || 1));
if ((bottom > myStorage.window.top) && (top < (myStorage.window.top + windowHeight))) {
if ($scope.reverse) {
parallax = windowHeight -parallax;
}
img.style.transform = 'translate(-50%, ' + Math.min(imgHeight, Math.max(0, parallax)) + 'px)';
}
};
function onImageLoad () {
img.removeEventListener('load', onImageLoad, false);
onUpdate();
img.style.opacity = $scope.opacity || 1;
};
document.addEventListener('scroll', onUpdate, false);
window.addEventListener('resize', onUpdate, false);
}
})]);
'use strict';
export default angular.module('myApp')
.factory('myStorage',
['$rootScope', '$log',
($rootScope, $log) => {
let obj = {
window: {
width: window.innerWidth,
height: window.innerHeight,
top: window.pageYOffset
}
};
window.addEventListener('resize', (event) => {
obj.window.width = window.innerWidth;
obj.window.height = window.innerHeight;
obj.window.top = window.pageYOffset;
});
return obj;
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment