Last active
August 29, 2015 14:21
-
-
Save sscovil/b9d0626582ce1abb8930 to your computer and use it in GitHub Desktop.
AngularJS Parallax Background Directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(angular) { | |
'use strict'; | |
var module = angular.module('sscovil.parallax', []); | |
// Requires jQuery for retreiving computed background-position from angular.element objects | |
// Alternative would be to use: window.getComputedStyle(scrollElem, null).backgroundPosition | |
module.directive('parallaxBackground', function($window) { | |
return { | |
restrict: 'A', | |
transclude: true, | |
template: '<div ng-transclude></div>', | |
scope: { | |
easing: '@', | |
scroll: '@' | |
}, | |
link: function($scope, elem, attrs) { | |
var easing = parseFloat($scope.easing || 20); | |
var scrollElem = $scope.scroll ? angular.element($scope.scroll) : angular.element($window); | |
var BackgroundPosition = function(calculated) { | |
var array = (calculated || '0px 0px').trim().split(' '); | |
var xUnitIsPixels = array[0].indexOf('px') !== -1; | |
var yUnitIsPixels = array.length > 1 && array[1].indexOf('px') !== -1; | |
// Only works with 'px' units; keywords and percentages evaluate to 0 | |
this.x = xUnitIsPixels ? parseFloat(array[0]) : 0; | |
this.y = yUnitIsPixels ? parseFloat(array[1]) : 0; | |
}; | |
var bgPositionString = elem.css('background-position'); | |
var bgPositionStringArray = bgPositionString.trim().split(/,\s*/); | |
var bgPositionObjectArray = []; | |
for (var i = 0; i < bgPositionStringArray.length; i++) { | |
bgPositionObjectArray.push(new BackgroundPosition(bgPositionStringArray[i])); | |
} | |
var setBackgroundPosition = function() { | |
var bgPosition = ''; | |
for (var i = 0; i < bgPositionObjectArray.length; i++) { | |
var scrollX = -(scrollElem.scrollLeft() / easing) + bgPositionObjectArray[i].x; | |
var scrollY = -(scrollElem.scrollTop() / easing) + bgPositionObjectArray[i].y; | |
if (i > 0) bgPosition += ', '; | |
bgPosition += scrollX + 'px '; | |
bgPosition += scrollY + 'px'; | |
} | |
elem.css('background-position', bgPosition); | |
}; | |
scrollElem.bind('load', function() { | |
setBackgroundPosition(); | |
$scope.$apply(); | |
}); | |
scrollElem.bind("scroll", setBackgroundPosition); | |
scrollElem.bind("touchmove", setBackgroundPosition); | |
} | |
}; | |
}); | |
})(angular); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment