-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
scrollTo.js
89 lines (72 loc) · 2.52 KB
/
scrollTo.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//@ts-check
import * as utils from './utils.js';
import { setScrolling } from './utilsFP.js';
import { state, setState } from "./state.js";
import { getOptions } from './options.js';
import { SLIDES_WRAPPER } from './selectors.js';
import { EventEmitter } from './eventEmitter.js';
let g_animateScrollId;
EventEmitter.on('bindEvents', bindEvents);
function bindEvents(){
EventEmitter.on('onDestroy', onDestroy);
}
function onDestroy(){
clearTimeout(g_animateScrollId);
}
/**
* Simulates the animated scrollTop of jQuery. Used when css3:false or scrollBar:true or autoScrolling:false
* http://stackoverflow.com/a/16136789/1081396
*/
export function scrollTo(element, to, duration, callback) {
var start = getScrolledPosition(element);
var change = to - start;
var currentTime = 0;
var increment = 20;
setState({activeAnimation: true});
var isCallbackFired = false;
// Making sure we can trigger a scroll animation
// when css scroll snap is active. Temporally disabling it.
if(element === document.body){
utils.css(document.body, {'scroll-snap-type': 'none'});
}
var animateScroll = function(){
if(state.activeAnimation){ //in order to stope it from other function whenever we want
var val = to;
currentTime += increment;
if(duration){
// @ts-ignore
val = window.fp_easings[getOptions().easing](currentTime, start, change, duration);
}
setScrolling(element, val);
if(currentTime < duration) {
clearTimeout(g_animateScrollId);
g_animateScrollId = setTimeout(animateScroll, increment);
}else if(typeof callback !== 'undefined' && !isCallbackFired){
callback();
isCallbackFired = true;
}
}else if (currentTime < duration && !isCallbackFired){
callback();
isCallbackFired = true;
}
};
animateScroll();
}
/**
* Getting the position of the element to scroll when using jQuery animations
*/
function getScrolledPosition(element){
var position;
//is not the window element and is a slide?
if(element.self != window && utils.hasClass(element, SLIDES_WRAPPER)){
position = element.scrollLeft;
}
else if(!getOptions().autoScrolling || getOptions().scrollBar){
position = utils.getScrollTop(getOptions());
}
else{
position = element.offsetTop;
}
//gets the top property of the wrapper
return position;
}