5

I have a fixed sidebar, which is visible all along the page when scrolling down.

The problem is that - in some cases - the sidebar is getting over the footer when reaching to the bottom of the page.

I want to hide the sidebar when the Footer is visible on screen to avoid that. How can I do it?

peterh
  • 9,698
  • 15
  • 68
  • 87
gargi
  • 229
  • 1
  • 7
  • 16

2 Answers2

6

Try this:

var isScrolledIntoView = function(elem) {
    var $elem = $(elem);
    var $window = $(window);

    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).on('scroll', function () {
    $('#sidebar').toggle(!isScrolledIntoView('#footer'));
});

Reference: Check if element is visible after scrolling

The function is called on window scroll and check if footer is visible. If visible, it hides sidebar else shows.

Community
  • 1
  • 1
Tushar
  • 78,625
  • 15
  • 134
  • 154
  • 1
    :visible checks that an element is not hidden, not that it is in view. http://api.jquery.com/visible-selector/ – Taplar Apr 25 '15 at 10:48
2

well... this is what I ended up with - works like a charm :)

$.fn.isVisible = function() {
    // Current distance from the top of the page
    var windowScrollTopView = $(window).scrollTop();

    // Current distance from the top of the page, plus the height of the window
    var windowBottomView = windowScrollTopView + $(window).height();

    // Element distance from top
    var elemTop = $(this).offset().top;

    // Element distance from top, plus the height of the element
    var elemBottom = elemTop + $(this).height();

    return ((elemBottom <= windowBottomView) && (elemTop >= windowScrollTopView));
}


$(document).ready(function() {
    $(window).scroll(function() {
        if($("#footer").isVisible()) {
            $("#sidebar").addClass('hiddensidebar');
        } else {
            $("#sidebar").removeClass('hiddensidebar');
        }
    });
});
gargi
  • 229
  • 1
  • 7
  • 16