Search code examples
jqueryfixedsidebar

JQuery fixed sidebar not working on long content


I have a wordpress website where in post page I have a jquery fixed sidebar. The fixed sidebar starts from the post section and stops at comment section.

I am using this jquery

$window = $(window),
    $sidebar = $("#side-scroller"),
    sidebarTop = $sidebar.position().top,
    sidebarHeight = $sidebar.height(),
    $footer = $("#comments"),
    footerTop = $footer.position().top,    
    $sidebar.addClass('fixed');

    function isScrolledIntoView(elem)
    {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();

        var elemTop = $(elem).offset().top;
        var elemBottom = elemTop + $(elem).height();

        return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
    }


    $window.scroll(function(event) {
        scrollTop = $window.scrollTop(),
        topPosition = Math.max(0, sidebarTop - scrollTop),
        topPosition = Math.min(topPosition, (footerTop - scrollTop) - sidebarHeight);
        $sidebar.css('top', topPosition);

        if(isScrolledIntoView('#comments')){
            $("#side-scroller").hide();
        }
        else{
            $("#side-scroller").show();
        }
    });

This works well, but when the post content is too long then it never stops at the comment section.

Here you can see the demo,

Normal post(where fixed sidebar works properly) http://webstutorial.com/html5-css3-toggle-slideup-slidedown/html-5

And long post(where sidebar keeps on scrolling) http://webstutorial.com/google-server-side-geocoding-php-infobox/website-tweaks/google

THIS IS NOT SPAM, OR LINK BUILDING, so please no down votes


Solution

  • I think it is working, however it is calculating the height incorrectly due to changes of the page after load.

    so if you move this into the $window.scroll function it should get the correct values on scroll.

    $footer = $("#comments"),
    footerTop = $footer.position().top;