jgallen23 / toc

Table of Contents Plugin
http://projects.jga.me/toc/
MIT License
531 stars 111 forks source link

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

Open moy opened 8 years ago

moy commented 8 years ago

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 commented 8 years ago

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