https://github.com/k-cermak/bootstrap-scrollspy-fixed
Bootstrap's default Scrollspy works horribly. This simple code will fix it.
https://github.com/k-cermak/bootstrap-scrollspy-fixed
bootstrap bootstrap5 fix hotfix hotfix-update javascript scrollspy scrollspy-nav
Last synced: about 2 months ago
JSON representation
Bootstrap's default Scrollspy works horribly. This simple code will fix it.
- Host: GitHub
- URL: https://github.com/k-cermak/bootstrap-scrollspy-fixed
- Owner: K-cermak
- License: other
- Created: 2023-07-07T19:07:44.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2024-07-18T20:23:25.000Z (almost 2 years ago)
- Last Synced: 2025-02-08T00:42:16.679Z (over 1 year ago)
- Topics: bootstrap, bootstrap5, fix, hotfix, hotfix-update, javascript, scrollspy, scrollspy-nav
- Language: JavaScript
- Homepage: https://karlosoft.com
- Size: 3.91 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# Fixed Bootstrap Scrollspy
* The basic Bootstrap [Scrollspy](https://getbootstrap.com/docs/5.3/components/scrollspy/#nested-nav) (nested nav) behaves poorly. Even when configured correctly, it often highlights the wrong links and doesn’t reflect the actual active element.
* Bootstrap generally tries to highlight whichever element occupies the largest visible portion of the screen. For example, if you have three short paragraphs taking up about 40% of the viewport and then a longer one that takes up more space, Scrollspy will mark the last paragraph as active simply because it dominates the screen — even though the first visible paragraph should be considered active.
* The code in this repository fixes that behavior and makes the highlighting far more intuitive.
## How to implement
* Remove these attributes from your code; everything else can remain unchanged:
`data-bs-target="#navbar-example3" data-bs-smooth-scroll="true" class="scrollspy-example-2" tabindex="0"`
* Insert the JS code from this repository into your page. It must be placed **after** the Scrollspy instance you are using (not before it).
* Adjust the selector so it points to the menu (nav) containing all relevant links. If your last paragraph is significantly longer, you may also want to adjust the value marked with `TODO: ...` in the code.
## How it works
* The script analyzes how much of each paragraph is visible and marks the first clearly visible one as active.
* The last paragraph is marked as active once it becomes at least partially visible. This is primarily to ensure that short final paragraphs can still be highlighted, but you can customize this behavior as needed.