-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathscroll-to.js
56 lines (48 loc) · 1.3 KB
/
scroll-to.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
import Ember from "ember";
export default Ember.Component.extend({
label: "",
tagName: null,
target: null,
offset: 0,
duration: 500,
didInsertElement() {
const self = this;
document.querySelector(`#${this.get("elementId")}`)
.addEventListener("click", function () {
self.scrollToTarget();
});
},
scrollToTarget() {
const target = this.get("target");
const offset = this.get("offset");
const duration = this.get("duration");
if (!target) {
Ember.Logger.error("Target should be passed");
return;
}
const targetPos = document.querySelector(target).offsetTop + offset;
this.animateScroll(targetPos, duration)
},
animateScroll(targetPos, duration) {
const self = this;
const startPos = window.scrollY;
const speed = 20;
let time = 0;
const animate = function () {
time += speed;
window.scrollTo(0, self.getAnimationPos(time, startPos, targetPos - startPos, duration));
if (time < duration) {
setTimeout(animate, speed);
}
};
animate();
},
getAnimationPos(time, startPos, endPos, duration) {
time /= duration / 2;
if (time < 1) {
return endPos / 2 * time * time + startPos;
}
time--;
return -endPos / 2 * (time * (time - 2) - 1) + startPos;
}
});