UNPKG

3.11 kBJavaScriptView Raw
1/* =============================================================
2 * bootstrap-scrollspy.js v1.4.0
3 * http://twitter.github.com/bootstrap/javascript.html#scrollspy
4 * =============================================================
5 * Copyright 2011 Twitter, Inc.
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============================================================== */
19
20
21!function ( $ ) {
22
23 "use strict"
24
25 var $window = $(window)
26
27 function ScrollSpy( topbar, selector ) {
28 var processScroll = $.proxy(this.processScroll, this)
29 this.$topbar = $(topbar)
30 this.selector = selector || 'li > a'
31 this.refresh()
32 this.$topbar.delegate(this.selector, 'click', processScroll)
33 $window.scroll(processScroll)
34 this.processScroll()
35 }
36
37 ScrollSpy.prototype = {
38
39 refresh: function () {
40 this.targets = this.$topbar.find(this.selector).map(function () {
41 var href = $(this).attr('href')
42 return /^#\w/.test(href) && $(href).length ? href : null
43 })
44
45 this.offsets = $.map(this.targets, function (id) {
46 return $(id).offset().top
47 })
48 }
49
50 , processScroll: function () {
51 var scrollTop = $window.scrollTop() + 10
52 , offsets = this.offsets
53 , targets = this.targets
54 , activeTarget = this.activeTarget
55 , i
56
57 for (i = offsets.length; i--;) {
58 activeTarget != targets[i]
59 && scrollTop >= offsets[i]
60 && (!offsets[i + 1] || scrollTop <= offsets[i + 1])
61 && this.activateButton( targets[i] )
62 }
63 }
64
65 , activateButton: function (target) {
66 this.activeTarget = target
67
68 this.$topbar
69 .find(this.selector).parent('.active')
70 .removeClass('active')
71
72 this.$topbar
73 .find(this.selector + '[href="' + target + '"]')
74 .parent('li')
75 .addClass('active')
76 }
77
78 }
79
80 /* SCROLLSPY PLUGIN DEFINITION
81 * =========================== */
82
83 $.fn.scrollSpy = function( options ) {
84 var scrollspy = this.data('scrollspy')
85
86 if (!scrollspy) {
87 return this.each(function () {
88 $(this).data('scrollspy', new ScrollSpy( this, options ))
89 })
90 }
91
92 if ( options === true ) {
93 return scrollspy
94 }
95
96 if ( typeof options == 'string' ) {
97 scrollspy[options]()
98 }
99
100 return this
101 }
102
103 $(document).ready(function () {
104 $('body').scrollSpy('[data-scrollspy] li > a')
105 })
106
107}( window.jQuery || window.ender );
\No newline at end of file