Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bootstrap scrollspy for in-page TOC #281

Closed
arnonzooz opened this issue Jun 5, 2020 · 3 comments
Closed

Bootstrap scrollspy for in-page TOC #281

arnonzooz opened this issue Jun 5, 2020 · 3 comments

Comments

@arnonzooz
Copy link

Hi

Has anyone managed to implement Bootstrap scrollspy with the right (in-page) toc generated by Docsy? If so, can you help me with some instructions cause I'm not managing to get it to work.

Here's the link to the Bootstrap scrollspy I'm trying to implement:

https://getbootstrap.com/docs/4.0/components/scrollspy/

Thanks!

@frodriguezsmartclip
Copy link

@arnonzooz
Copy link
Author

Trying it. I'm adding the following to body-end.html in the theme (partial/hooks/body-end.html):

<script>
    $('body').scrollspy({ target: '#TableOfContents' })
</script>

Still doesn't seem to work.

Should I expect an active class to be added to each toc entry? Or should it work out of the box (in which case I'd expect the TOC entry to be highlighted as I scroll)?

Thanks!

@arnonzooz
Copy link
Author

Couldn't get the Bootstrap scrollspy to work, but the following code does the job. Add it to body-end.html and don't forget to add some styling to the activeToc class.

<script>
    window.addEventListener("load", (event) => {
        createObserver();
    }, false);

    function createObserver() {
        let observer;

        let options = {
            root: null,
            rootMargin: '5px 5px -50%'
        };

        observer = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                const id = entry.target.getAttribute('id');
                if (entry.intersectionRatio > 0) {
                    document.querySelector(`nav li a[href="#${id}"]`).classList.add('activeToc');
                } else {
                    document.querySelector(`nav li a[href="#${id}"]`).classList.remove('activeToc');
                }
            });
            
        },options);
            document.querySelectorAll('h2[id], h3[id]').forEach((section) => {
                observer.observe(section);
            });
    }

</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants