Last active
August 29, 2015 14:20
-
-
Save weisk/4012493315dc710dd1cd to your computer and use it in GitHub Desktop.
Angular Parallax image & background
This file contains hidden or 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
angular.module 'directives' | |
### Usage: | |
<div | |
parallax-background | |
parallax-background-ratio="0.6" | |
parallax-background-src="assets/image.png" | |
parallax-background-gradient="linear-gradient(rgba(0, 0, 0, 0) 60%, rgba(0, 0, 0, 0.4) 100%)"> | |
</div> | |
### | |
.directive 'parallaxBackground', ($window, $parse) -> | |
restrict: 'A' | |
compile: (tEl, tAttrs, tFn) -> | |
parseSrc = $parse tAttrs.parallaxBackgroundSrc | |
(scope, elem, attrs) -> | |
src = parseSrc scope | |
gradient = attrs.parallaxBackgroundGradient | |
parallaxRatio = attrs.parallaxBackgroundRatio or 1.1 | |
img = new Image() | |
img.src = src | |
img.onload = -> | |
if gradient | |
elem.css 'background-image', "#{ gradient }, url(#{ src })" | |
else | |
elem.css 'background-image', "url(#{ src })" | |
setPosition() | |
setBindings() | |
setBindings = -> | |
$($window).bind 'scroll', setPosition | |
$($window).bind 'touchmove', setPosition | |
setPosition = -> | |
initialOffset = elem.prop 'offsetTop' | |
currentOffset = $window.pageYOffset | |
if currentOffset > initialOffset | |
newOffset = ($window.pageYOffset - initialOffset) * parallaxRatio | |
else | |
newOffset = 0 | |
elem.css 'transform', "translate(0px, #{ newOffset.toFixed(2) }px)" | |
# $window.requestAnimationFrame -> elem.css 'transform', "translate(0px, #{ newOffset.toFixed(2) }px)" | |
# elem.css 'background-position', "0 #{ newOffset }px" | |
### Usage | |
<img | |
src="assets/image.png" | |
parallax-image | |
parallax-ratio="0.6"/> | |
### | |
.directive 'parallaxImage', ($window) -> | |
restrict: 'A' | |
link: (scope, elem, attrs) -> | |
parallaxRatio = attrs.parallaxRatio or 1.1 | |
parallaxVerticalOffset = attrs.parallaxVerticalOffset | |
parallaxHorizontalOffset = attrs.parallaxHorizontalOffset | |
setBindings = -> | |
$($window).bind 'scroll', setPosition | |
$($window).bind 'touchmove', setPosition | |
setPosition = -> | |
initialOffset = elem.prop 'offsetTop' | |
currentOffset = $window.pageYOffset | |
if currentOffset > initialOffset | |
newOffset = ($window.pageYOffset - initialOffset) * parallaxRatio | |
else | |
newOffset = 0 | |
elem.css 'transform', "translate(0px, #{ newOffset }px)" | |
setPosition() | |
setBindings() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment