diff --git a/js/src/scrollspy.js b/js/src/scrollspy.js index 83080e800f6e..f4d6671013b0 100644 --- a/js/src/scrollspy.js +++ b/js/src/scrollspy.js @@ -112,6 +112,13 @@ class ScrollSpy extends BaseComponent { // TODO: on v6 target should be given explicitly & remove the {target: 'ss-target'} case config.target = getElement(config.target) || document.body + // TODO: v6 Only for backwards compatibility reasons. Use rootMargin only + config.rootMargin = config.offset ? `${config.offset}px 0px -30%` : config.rootMargin + + if (typeof config.threshold === 'string') { + config.threshold = config.threshold.split(',').map(value => Number.parseFloat(value)) + } + return config } @@ -144,7 +151,7 @@ class ScrollSpy extends BaseComponent { const options = { root: this._rootElement, threshold: this._config.threshold, - rootMargin: this._getRootMargin() + rootMargin: this._config.rootMargin } return new IntersectionObserver(entries => this._observerCallback(entries), options) @@ -189,11 +196,6 @@ class ScrollSpy extends BaseComponent { } } - // TODO: v6 Only for backwards compatibility reasons. Use rootMargin only - _getRootMargin() { - return this._config.offset ? `${this._config.offset}px 0px -30%` : this._config.rootMargin - } - _initializeTargetsAndObservables() { this._targetLinks = new Map() this._observableSections = new Map() diff --git a/js/tests/unit/scrollspy.spec.js b/js/tests/unit/scrollspy.spec.js index 61edeb921a49..b1c805303326 100644 --- a/js/tests/unit/scrollspy.spec.js +++ b/js/tests/unit/scrollspy.spec.js @@ -132,7 +132,7 @@ describe('ScrollSpy', () => { ' One' + '', '
', - ' ', + ' ', '
' ].join('') @@ -144,6 +144,31 @@ describe('ScrollSpy', () => { expect(scrollSpy._observer.thresholds).toEqual([1]) }) + it('should respect threshold option mark-up', () => { + fixtureEl.innerHTML = [ + '', + '
', + ' ', + '
' + ].join('') + + const scrollSpy = new ScrollSpy('#content', { + target: '#navigation' + }) + + const expectToBeCloseToArray = (actual, expected) => { + expect(actual.length).toBe(expected.length) + for (const x of actual) { + const i = actual.indexOf(x) + expect(x).withContext(`[${i}]`).toBeCloseTo(expected[i]) + } + } + + expectToBeCloseToArray(scrollSpy._observer.thresholds, [0, 0.2, 1]) + }) + it('should not take count to not visible sections', () => { fixtureEl.innerHTML = [ '