Last active
October 3, 2018 14:51
-
-
Save DevEarley/74135544b3c033d66e341ccd16e91916 to your computer and use it in GitHub Desktop.
Angular Directive watches page scroll w/ debounce feature
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
'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