Skip to content

Instantly share code, notes, and snippets.

@DevEarley
Last active October 3, 2018 14:51
Show Gist options
  • Save DevEarley/74135544b3c033d66e341ccd16e91916 to your computer and use it in GitHub Desktop.
Save DevEarley/74135544b3c033d66e341ccd16e91916 to your computer and use it in GitHub Desktop.
Angular Directive watches page scroll w/ debounce feature
'use strict';
angular.module('someApp').directive('simpleAffix', ['$window',function ($window) {
return {
scope: {
onAffix: "&",
onUnaffix: "&",
affixHeight:"="
},
restrict: 'A',
link: function (scope, element, attrs)
{
var fixed = false;
scope.onUnaffix()
angular.element($window).bind("scroll", function ()
{
if (fixed == false && scope.affixHeight < $window.pageYOffset) {
fixed = true;
scope.$apply(scope.onAffix());
return
}
if (fixed == true && scope.affixHeight >= $window.pageYOffset) {
fixed = false;
scope.$apply(scope.onUnaffix());
}
});
}
};
}]);
angular.module('someApp').directive('rangeAffix', ['$window',function ($window) {
return {
scope: {
onAffix: "&"
},
restrict: 'A',
link: function (scope, element, attrs)
{
let fixed = false;
function scrollHandler() {
let _boundingClientRect = element[0].getBoundingClientRect();
let _top = _boundingClientRect.top;
let _bottom = _boundingClientRect.bottom;
if (_bottom >= $window.innerHeight/2 && $window.innerHeight/2 >= _top ) {
scope.$apply(scope.onAffix());
return
}
}
angular.element($window).bind("scroll", debounce(scrollHandler,10));
}
};
}]);
function debounce(func, wait) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
func.apply(context, args);
};
if (!timeout) func.apply(context, args);
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment