From e8af21cc9db7941de217113cef5c7d1640dd86d5 Mon Sep 17 00:00:00 2001 From: Tadeu Zagallo Date: Fri, 23 May 2014 19:27:05 -0300 Subject: [PATCH] Clear scrollspy selection above first section Closes #13563 by merging it. --- js/scrollspy.js | 15 ++++++++----- js/tests/unit/scrollspy.js | 43 +++++++++++++++++++++++++++++++++++++- 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/js/scrollspy.js b/js/scrollspy.js index db2378787e..430b5d6aac 100644 --- a/js/scrollspy.js +++ b/js/scrollspy.js @@ -91,8 +91,9 @@ return activeTarget != (i = targets[targets.length - 1]) && this.activate(i) } - if (activeTarget && scrollTop <= offsets[0]) { - return activeTarget != (i = targets[0]) && this.activate(i) + if (activeTarget && scrollTop < offsets[0]) { + this.activeTarget = null + return this.clear() } for (i = offsets.length; i--;) { @@ -106,9 +107,7 @@ ScrollSpy.prototype.activate = function (target) { this.activeTarget = target - $(this.selector) - .parentsUntil(this.options.target, '.active') - .removeClass('active') + this.clear() var selector = this.selector + '[data-target="' + target + '"],' + @@ -127,6 +126,12 @@ active.trigger('activate.bs.scrollspy') } + ScrollSpy.prototype.clear = function () { + $(this.selector) + .parentsUntil(this.options.target, '.active') + .removeClass('active') + } + // SCROLLSPY PLUGIN DEFINITION // =========================== diff --git a/js/tests/unit/scrollspy.js b/js/tests/unit/scrollspy.js index a54263608d..46e2a1b855 100644 --- a/js/tests/unit/scrollspy.js +++ b/js/tests/unit/scrollspy.js @@ -73,7 +73,7 @@ $(function () { $scrollspy.scrollTop(350) }) - test('middle navigation option correctly selected when large offset is used', function () { + test('should correctly select middle navigation option when large offset is used', function () { stop() var sectionHTML = '' @@ -142,4 +142,45 @@ $(function () { .then(function () { return testElementIsActiveAfterScroll('#li-2', '#div-2') }) }) + test('should clear selection if above the first section', function () { + stop() + + var sectionHTML = '' + + '' + var $section = $(sectionHTML).appendTo('#qunit-fixture') + + var scrollspyHTML = '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + var $scrollspy = $(scrollspyHTML).appendTo('#qunit-fixture') + + $scrollspy + .bootstrapScrollspy({ + target: '#navigation', + offset: $scrollspy.position().top + }) + .one('scroll.bs.scrollspy', function () { + strictEqual($('.active').length, 1, '"active" class on only one element present') + strictEqual($('.active').has('#two-link').length, 1, '"active" class on second section') + + $scrollspy + .one('scroll.bs.scrollspy', function () { + strictEqual($('.active').length, 0, 'selection cleared') + start() + }) + .scrollTop(0) + }) + .scrollTop(201) + }) + })