forked from d-oliveros/ngSticky
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sticky.js
72 lines (60 loc) · 1.55 KB
/
sticky.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
angular.module('sticky', [])
.directive('sticky', ['$timeout', function($timeout){
return {
restrict: 'A',
scope: {
offset: '@',
stickyClass: '@'
},
link: function($scope, $elem, $attrs){
$timeout(function(){
var offsetTop = $scope.offset || 0,
stickyClass = $scope.stickyClass || '',
$window = angular.element(window),
doc = document.documentElement,
initialPositionStyle = $elem.css('position'),
stickyLine,
scrollTop;
// Set the top offset
//
$elem.css('top', offsetTop+'px');
// Get the sticky line
//
function setInitial(){
stickyLine = $elem[0].offsetTop - offsetTop;
checkSticky();
}
// Check if the window has passed the sticky line
//
function checkSticky(){
scrollTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
if ( scrollTop >= stickyLine ){
$elem.addClass(stickyClass);
$elem.css('position', 'fixed');
} else {
$elem.removeClass(stickyClass);
$elem.css('position', initialPositionStyle);
}
}
// Handle the resize event
//
function resize(){
$elem.css('position', initialPositionStyle);
$timeout(setInitial);
}
// Remove the listeners when the scope is destroyed
//
function onDestroy(){
$window.off('scroll', checkSticky);
$window.off('resize', resize);
}
// Attach our listeners
//
$scope.$on('$destroy', onDestroy);
$window.on('scroll', checkSticky);
$window.on('resize', resize);
setInitial();
});
},
};
}]);