-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathoverscroll.js
67 lines (56 loc) · 1.99 KB
/
overscroll.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
// JavaScript Document
(function(){
// Declare variables
var touch_x, touch_y, obj_x, obj_y, speed_x=0, speed_y=0, scrollanim;
document.addEventListener('touchstart', function(e) {
clearInterval(scrollanim);
// Get Touch target
obj_x = e.target
obj_y = e.target
// Get the target parent that is scrollable
while ((window.getComputedStyle(obj_x)['overflow-x'] != "auto" && window.getComputedStyle(obj_x)['overflow-x'] != "scroll") || obj_x.parentNode == null) {
obj_x = obj_x.parentNode
}
while ((window.getComputedStyle(obj_y)['overflow-y'] != "auto" && window.getComputedStyle(obj_y)['overflow-y'] != "auto") || obj_y.parentNode == null) {
obj_y = obj_y.parentNode
}
// Get if no scrollable parents are present set null
if (obj_x.parentNode == null) obj_x = null;
if (obj_y.parentNode == null) obj_y = null;
// Get the touch starting point
var touch = e.touches[0];
touch_x = touch.pageX;
touch_y = touch.pageY;
}, false);
document.addEventListener('touchmove', function(e) {
// Clear animation
clearInterval(scrollanim);
// Prevent window scrolling
e.preventDefault();
// Scroll according to movement
var touch = e.touches[0];
obj_x.scrollLeft = obj_x.scrollLeft - (touch.pageX - touch_x)
obj_y.scrollTop = obj_y.scrollTop - (touch.pageY - touch_y)
// Set speed speed
speed_x = (touch.pageX - touch_x)
speed_y = (touch.pageY - touch_y)
// Set new positon
touch_x = touch.pageX;
touch_y = touch.pageY;
}, false);
// Add a final animation as in iOS
document.addEventListener('touchend', function(e) {
// Clear previous animations
clearInterval(scrollanim);
// Animate
scrollanim = setInterval(function() {
obj_x.scrollLeft = obj_x.scrollLeft - speed_x
obj_y.scrollTop = obj_y.scrollTop - speed_y
// Decelerate
speed_x = speed_x * 0.9;
speed_y = speed_y * 0.9;
// Stop animation at the end
if (speed_x < 1 && speed_x > -1 && speed_y < 1 && speed_y > -1) clearInterval(scrollanim)
},15)
}, false);
})();