-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscrollWhen.js
More file actions
65 lines (53 loc) · 1.92 KB
/
Copy pathscrollWhen.js
File metadata and controls
65 lines (53 loc) · 1.92 KB
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
(function () {
'use strict';
angular.module('bb.scrollWhen', []);
angular.module('bb.scrollWhen').directive('scrollWhen', scrollWhen);
scrollWhen.$inject = ['$timeout'];
function scrollWhen($timeout) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var scrollWatchEnabled = (attrs.scrollWatchEnabled === 'true');
// Do the initial check to scroll (this will be hit on state change/page load)
$timeout(function () {
evalScroll();
}, 0);
// Enable this to add watchers to the items so that when the expression evaluates to true it will scroll to your item
if (scrollWatchEnabled) {
scope.$watch(attrs.scrollWhen, function(newVal, oldVal) {
if (newVal !== oldVal) {
evalScroll();
}
});
}
// Evaluate the expression and scroll if we need to
function evalScroll() {
if (scope.$eval(attrs.scrollWhen)) {
var scrollContainer = attrs.scrollContainer || 'body';
var scrollSpeed = attrs.scrollSpeed || 500;
var scrollOffset = attrs.scrollOffset || 600;
var $element = $(scrollContainer);
var scrollPos = getPosition(element[0]);
doScroll($element, (scrollPos.y - scrollOffset), scrollSpeed);
}
}
// Scroll to the element
function doScroll($element, scrollPos, scrollSpeed) {
$element.animate({
scrollTop : scrollPos
}, scrollSpeed);
}
function getPosition(element) {
var x = 0;
var y = 0;
while(element) {
x += (element.offsetLeft - element.scrollLeft + element.clientLeft);
y += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: x, y: y };
}
}
}
}
})();