Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

jquery

css

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?

like image 880
gargi Avatar asked Apr 25 '15 10:04

gargi


People also ask

How do I hide a div after some time?

Approach: Select the div element. Use delay function (setTimeOut(), delay()) to provide the delay to hide() the div element.

How to fix overflowing div?

Add a padding top on the #scrollable div and make the #menu div absolute. Add a z-index to the #menu div so it stays on top. Also, make sure to add box-sizing: border-box on all elements to prevent exceeding the assigned sizes. Save this answer.

How do I make a Div always stay on top?

The vertical position of the element to be stuck can also be modified with the help of the 'top' property. It can be given a value of '0px' to make the element leave no space from the top of the viewport, or increased further to leave space from the top of the viewport.


2 Answers

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.

like image 150
Tushar Avatar answered Sep 30 '22 15:09

Tushar


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');
        }
    });
});
like image 28
gargi Avatar answered Sep 30 '22 16:09

gargi