Last active
August 29, 2015 14:24
-
-
Save MrJackdaw/be9f9f30424d51a1d7b5 to your computer and use it in GitHub Desktop.
A small AngularJS directive (ng-1.3.x+) for affixing an element on page scroll
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
'use strict'; | |
/** | |
* 'FIX ELEMENT': Locks element to specified coordinates (or window top) | |
* Optional Directive Attributes: | |
* [number] top: Fixed Element's distance from top (px), | |
* [number] left: Fixed Element's distance from left (px), | |
* [number] right: Fixed Element's distance from right (px), | |
* [number] padStart: Additional px padding used to calculate when the fix should be triggered | |
* [string] target: CSS selector of a sibling element. | |
* Target element gets padding to offset the removal of the fixed element, | |
* which mitigates page-jerk when the fix is triggered | |
*/ | |
app.directive('fixElem', function($window) { | |
return { | |
restrict: 'A', | |
scope: { | |
top: '@', | |
left: '@', | |
right: '@', | |
target: '@', | |
padStart: '@' | |
}, | |
link: function(scope, elem) { | |
var e = elem[0], | |
top = scope.top || 0, | |
left = scope.left || 0, | |
right = scope.right || 0, | |
target, start; | |
angular.element($window) | |
.bind('load', function() { | |
// Search for target | |
target = scope.target && document.querySelector(scope.target); | |
target = angular.element(target)[0]; | |
}) | |
.bind('scroll', function() { | |
start = (e.offsetHeight + (parseInt(scope.padStart) || 0)) - top; | |
if ($window.scrollY >= start) { | |
elem.addClass('fixed'); | |
// Override or remove if you want to | |
// handle styling with .fixed class | |
e.style.top = top + 'px'; | |
e.style.left = left + 'px'; | |
e.style.right = right + 'px'; | |
e.style.zIndex = 1001; | |
if (target) target.style.paddingTop = (e.offsetHeight + 10) + 'px'; | |
} else { | |
elem.removeClass('fixed'); | |
// Optional if you aren't injecting inline styles above | |
e.removeAttribute('style'); | |
// Reset 'target' sibling's padding offset | |
if (target) target.style.paddingTop = ''; | |
} | |
}); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment