-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathjquery.scroller.js
91 lines (80 loc) · 2.73 KB
/
jquery.scroller.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
90
91
/*
* jQuery SPA scrolling menu plugin
* http://github.com/rokasLeng/scroller
*
* Copyright (c) 2015 Rokas Lengvenis
* Dual licensed under the MIT and GPL licenses.
* Uses the same license as jQuery, see:
* http://jquery.org/license
*
* @version 1.0.0
*
* Example usage:
* $('#menu').scroller({
* scrollSpeed: 750,
* menuClassName: 'scroller'
* });
*/
(function ($) {
$.fn.scroller = function (options) {
var settings = $.extend({
scrollSpeed: 750,
menuClassName: 'scroller',
activeClass: 'active'
}, options);
// Local vars
var scrollSpeed = settings.scrollSpeed;
var activeClass = settings.activeClass;
var menuClassName = settings.menuClassName;
this.addClass(menuClassName);
var menu = $('.' + menuClassName);
var menuLinks = $('.' + menuClassName + ' a');
var menuTop = menu.offset().top;
var sectionPos = [];
$(window).scroll(function () {
if (menuTop < $(window).scrollTop()) {
menu.addClass('fixed');
$('body').css('padding-top', menu.height());
} else if (menuTop > $(window).scrollTop()) {
menu.removeClass('fixed');
$('body').css('padding-top', 0);
}
// If it is bottom of the page and last section is smaller then viewport height
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
menuLinks.removeClass(activeClass);
sectionPos[sectionPos.length - 1].link.addClass(activeClass);
} else {
// Get active section and make appropriate link active
sectionPos.forEach(function (pos) {
if ($(window).scrollTop() >= pos.top && $(window).scrollTop() < pos.bottom) {
menuLinks.removeClass(activeClass);
pos.link.addClass(activeClass);
// When position above sections remove active links
} else if ($(window).scrollTop() < sectionPos[0].top) {
menuLinks.removeClass(activeClass);
}
});
}
});
return menuLinks.each(function (index) {
// Get section id
var id = $(this).attr('href').substr(1);
// Get section active area position
var top = $('#' + id).offset().top - menu.height();
var bottom = top + $('#' + id).height();
sectionPos.push({
link: $(this),
top: top,
bottom: bottom
});
$(this).on('click', function (e) {
e.preventDefault();
// Move to a given section
var sectionOffset = $("#" + id).offset().top - menu.height();
console.log(sectionPos);
// ScrollTop has to be integer value, and fractional offset can be returned in chrome
$('html, body').animate({scrollTop: Math.ceil(sectionOffset)}, scrollSpeed);
});
});
};
}(jQuery));