display a sidebar when scrolling only from point to another in javascript or jquery

  css, javascript, jquery, sidebar

I would like to display a sidebar only from the bottom of section to before the footer, so the sidebar doesn’t overlap the top part (header + section "head") and the footer.
I tried several stuffs in js and jquery, but it doesn’t work. Someone could help me?

css

.sidenav {
  width: 20rem;
  position: fixed;
  z-index: 1;
  top: 10rem;
  right: 5rem;
  overflow-x: hidden;
}

html structure

<header>
</header>
<main>
  <section class="head container" id="head"></section>
  <section class="container"></section>
  <aside id="sidenav" class="sidenav container"></aside>
</main>
<footer></footer>

js

        let headerHeight = $("header").height();
        let headHeight = $(".head").height();
        let topHeight = headerHeight + headHeight;
        
        let sidebarOffset = $('#sidenav').offset().top;
        let sidebarHeight = $('#sidenav').outerHeight(true);
        let footerOffset = $('footer').offset().top;
        let footerHeight = $('footer').outerHeight(true);
        let bottom = sidebarHeight + footerHeight;
        let bottomOffset = sidebarOffset+ footerOffset;
        let page = $(document).height();
        
        $(window).scroll(function(evt) {
          let y = $(this).scrollTop();
            if(y > topHeight && y < (page - bottom)) {
              $('#sidenav').css("top", "10rem");
            } else {
              $('#sidebar').css("top", "-500rem");
            }
        
        });

        // // vanilla js
        // window.onscroll = function() {scrollFunction()};
        // function scrollFunction() {
        //   let headerHeight = document.getElementsByTagName("header").offsetHeight;
        //   let headHeight = document.getElementById("head").offsetHeight;
        //   let topHeight = headerHeight + headHeight;
        
        //   let sidebarHeight = document.getElementById("sidenav").offsetHeight;
        //   let footerHeight = document.getElementsByTagName("footer").offsetHeight;
        //   let bottom = sidebarHeight + footerHeight;
        
        //   let page = window.innerHeight;
        
        //   if (document.body.scrollTop > topHeight && documentElement.scrollTop < (page - bottom)) {
        //     document.getElementById("sidenav").style.top = "10rem";
        //   } else {
        //     document.getElementById("sidenav").style.top = "-500rem";
        //   }
        // }

Source: Ask Javascript Questions

LEAVE A COMMENT