Skip to content

Instantly share code, notes, and snippets.

@mcranston18
Created October 30, 2013 15:15
Show Gist options
  • Save mcranston18/7234357 to your computer and use it in GitHub Desktop.
Save mcranston18/7234357 to your computer and use it in GitHub Desktop.
Angular directive for scroll spy
'use strict';
angular.module('AppSuccess')
.directive('scrollSpy', ['$window', function ($window) {
return {
restrict: 'A',
link: function (scope, element) {
// Get offset before scrollSpy activates
// otherwise offset of element would change
var elmOffset = $(element).offset().top;
// Track if window scroll passes element offset
var scrollSpy = function() {
var windowScroll = $window.scrollY;
if ( windowScroll > elmOffset ) {
element.addClass('sticky');
} else {
element.removeClass('sticky');
}
};
// Throttled so it doesn't fire all the time
var throttledScrollSpy = _.throttle(scrollSpy, 100);
angular.element($window).bind('scroll', throttledScrollSpy);
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment