Home > Back-end >  Show and hide the footer element when scrolling to the bottom of the page
Show and hide the footer element when scrolling to the bottom of the page

Time:09-30

I have a structure like this: enter image description here

As you can see, I have a fixed nav-bar at the top of the page and a drop down sidebar. Then I have a <div> element with content id.

Inside this <div> element I have some content, and finally, I have a <div> with a fixed position to the bottom of the page.

What I want is to hide the bottom div when the user scrolls down to the bottom of the page.

I have tried this but it doesn't work as I expected:

    $('div#content').scroll(function () {
        var fixedBottom = $("#dialog-button-bar");
        if ($('div#content').height() <= ($(window).height()   $(window).scrollTop())) {
            fixedBottom.css("opacity", 0 );
        } else {
            fixedBottom.css("opacity", 1 );
        }
    });

I hope to someone can help me. Thanks

CodePudding user response:

You are adding the scollTop to the height constantly, would this not always make the if statement true, as the height some value is always bigger than the divs height. Try comparing the documents height to the scrollTop and not the divs height

CodePudding user response:

This is a tricky one because scrollTop() and height() jQuery methods change their returned value when adding and removing an HTML element.

One way of doing this is by defining a boolean variable that will help avoid the document height to be changed when adding the footer. And so, by doing this is possible to create an if statement that will change the CSS attribute display according to the scroll position.

let footerVisible = false;
var docHeight = 0;

$(window).scroll(function() {
   var scrollPos = $(window).scrollTop()   $(window).height();
   if(footerVisible == false){docHeight = $(document).height()}
   
   if(scrollPos >= docHeight){
    footerVisible = true;
    $('.footer').css('display', 'block');
   }else if(scrollPos <= docHeight){
    footerVisible = false;
    $('.footer').css('display', 'none');
   }
});
*{width:100%;margin:0;padding:0;color:white;text-align:center}
.nav{
  background: #00A19D;
  height:60px;
}
.content{
  background: #FFF8E5;
  height:1500px;
}
.footer{
  background: #345B63;
  height:200px;
  display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class='nav'><br><h1>Nav</h1></section>
<section class='content'></section>
<section class='footer'><br><h1>Magical Footer</h1></section>

  • Related