gargi
gargi

Reputation: 259

How to hide fixed DIV when footer is visible on screen?

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?

Upvotes: 5

Views: 5532

Answers (2)

Tushar
Tushar

Reputation: 87203

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.

Upvotes: 6

gargi
gargi

Reputation: 259

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');
        }
    });
});

Upvotes: 3

Related Questions