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

Let the TOC scroll to the highlighted section if needed [POC solution included] #56

Open
moy opened this issue Jul 20, 2016 · 1 comment

Comments

@moy
Copy link

moy commented Jul 20, 2016

Hi, and thanks for this great piece of code!

I had a minor issue with a long document, where the TOC (as a sidebar) was not fitting in the screen: then, the highlighted section was not always on screen, which partly defeats the purpose of the "Automatically highlight the current section" feature.

I used the following code to let the table of contents scroll automatically to the highlighted section when it's not visible:

function isElementInViewport (el) {
    // special bonus for those using jQuery
    if (typeof jQuery === "function" && el instanceof jQuery) {
        el = el[0];
    }

    var rect = el.getBoundingClientRect();

    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
    );
}

$(function(){
    $('#table-of-contents').toc({
        'onHighlight': function(el) {
        // Scroll to make the element visible if needed.
            if (!isElementInViewport(el)) {
                $('#table-of-contents').animate({
                        scrollTop: el.offset().top
                    }, 2000);
            }
        }
    });
});

It would be nice to have the feature built-in (just a 'highlightAutoScroll' : true passed to toc() for example).

Waiting for that, other people may find the code above useful :-). Feel free to use it.

@jgallen23
Copy link
Owner

thanks for sharing! I think this is a great solution for this problem.

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