forked from Jamedjo/angular-sticky
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sticky.js
66 lines (56 loc) · 2.05 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
angular.module("sticky", []).directive("sticky", ['$window', '$timeout', function($window, $timeout) {
return {
link: function(scope, element, attrs) {
var $win = angular.element($window);
if (scope._stickyElements === undefined) {
scope._stickyElements = [];
$win.bind("scroll.sticky", function(e) {
var pos = $win.scrollTop();
for (var i=0; i<scope._stickyElements.length; i++) {
var item = scope._stickyElements[i];
if (!item.isStuck && pos > item.start) {
item.element.css({ width: item.element.outerWidth(false) + "px" });
item.element.addClass("stuck");
item.isStuck = true;
if (item.placeholder) {
item.placeholder = angular.element("<div></div>")
.css({height: item.element.outerHeight(false) + "px"})
.insertBefore(item.element);
}
}
else if (item.isStuck && pos < item.start) {
item.element.removeClass("stuck");
item.element.css({ width: "auto" });
item.isStuck = false;
if (item.placeholder) {
item.placeholder.remove();
item.placeholder = true;
}
}
}
});
var recheckPositions = function() {
for (var i=0; i<scope._stickyElements.length; i++) {
var item = scope._stickyElements[i];
if (!item.isStuck) {
item.start = item.element.offset().top;
} else if (item.placeholder) {
item.start = item.placeholder.offset().top;
}
}
};
$win.bind("load", recheckPositions);
$win.bind("resize", recheckPositions);
}
$timeout(function(){
var item = {
element: element,
isStuck: false,
placeholder: attrs.usePlaceholder !== undefined,
start: element.offset().top
};
scope._stickyElements.push(item);
});
}
};
}]);