From 62b3d3cc68b969c9328e127aea3cbbd1682aa0a4 Mon Sep 17 00:00:00 2001 From: GeoSot Date: Tue, 12 Jul 2022 02:17:53 +0300 Subject: [PATCH] Add some details for non visible scrollspy elements (#36625) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * docs: add some details for non visible scrollspy elements * Apply suggestions from code review Co-authored-by: Julien Déramond * fix selectors on snippet * Fix paragraph by a native speaker Co-authored-by: Mark Otto * Update scrollspy.md * Move from warning to own section * Update scrollspy.md Co-authored-by: Julien Déramond Co-authored-by: Julien Déramond Co-authored-by: Mark Otto Co-authored-by: Mark Otto --- site/content/docs/5.2/components/scrollspy.md | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/site/content/docs/5.2/components/scrollspy.md b/site/content/docs/5.2/components/scrollspy.md index abbb596dfe..5e329dc85a 100644 --- a/site/content/docs/5.2/components/scrollspy.md +++ b/site/content/docs/5.2/components/scrollspy.md @@ -16,9 +16,7 @@ Scrollspy toggles the `.active` class on anchor (``) elements when the elemen - As you scroll the "spied" container, an `.active` class is added and removed from anchor links within the associated navigation. Links must have resolvable `id` targets, otherwise they're ignored. For example, a `home` must correspond to something in the DOM like `
` -- Target elements that aren't visible will be ignored and their corresponding nav items will never receive an `.active` class. - -Checkout the examples below to see it in action. +- Target elements that are not visible will be ignored. See the [Non-visible elements](#non-visible-elements) section below. ## Examples @@ -330,6 +328,20 @@ Scrollspy is not limited to nav components and list groups, so it will work on a ``` +## Non-visible elements + +Target elements that aren’t visible will be ignored and their corresponding nav items won't receive an `.active` class. Scrollspy instances initialized in a non-visible wrapper will ignore all target elements. Use the `refresh` method to check for observable elements once the wrapper becomes visible. + +```js +document.querySelectorAll('#nav-tab>[data-bs-toggle="tab"]').forEach(el => { + el.addEventListener('shown.bs.tab', () => { + const target = el.getAttribute('data-bs-target') + const scrollElem = document.querySelector(`${target} [data-bs-spy="scroll"]`) + bootstrap.ScrollSpy.getOrCreateInstance(scrollElem).refresh() + }) +}) +``` + ## Usage ### Via data attributes