-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhide-show-back-to-top.js
47 lines (43 loc) · 1.44 KB
/
hide-show-back-to-top.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
/* helper function to show back-to-top button only if user navigates up
and hides otherwise after 2s
*/
function scrollToTop() {
var lastTop = $(this).scrollTop();
var scrollTopVisible = false;
var timeout = null;
var targetSelector = '#back_to_top';
$(window).on('scroll', function () {
var currentTop = $(this).scrollTop();
if (currentTop > 200 && currentTop + 20 < lastTop && !scrollTopVisible) {
scrollTopVisible = true;
$(targetSelector).fadeIn();
timeout = setTimeout(function () {
scrollTopVisible = false;
$(targetSelector).fadeOut();
}, 2000);
}
else if (currentTop < 200 && scrollTopVisible) {
clearTimeout(timeout);
scrollTopVisible = false;
$(targetSelector).fadeOut();
}
else if (scrollTopVisible && timeout) {
clearTimeout(timeout);
timeout = setTimeout(function () {
scrollTopVisible = false;
$(targetSelector).fadeOut();
}, 2000);
}
lastTop = currentTop;
});
$(targetSelector).click(function (event) {
event.preventDefault();
if (timeout) clearTimeout(timeout);
$('body, html').animate({
scrollTop: 0
}, 800, 'swing', function () {
scrollTopVisible = false;
$(targetSelector).fadeOut();
});
});
}