简体   繁体   中英

how to make a section fixed on scroll and scroll up with footer

I was fetching this problem for several projects. I try to find the solution on StackOverflow but there are two parts

  1. on the scroll fixed
  2. scroll up with the footer
  3. and Finally, find out and try to share.

hope it will help others.

<div class="col-md-5 offset-md-1">
    <div id="listing_preview">
...
    </div>
</div>

Footer

<footer class="p-5 footer">
....
</footer>

I research this problem and find out this solution. CSS

<style>
div.sticky {
    position: fixed;
    top: 50px;
}
</style>
<script>
    window.onscroll = function() {myFunction()};
    
    var product_preview = document.getElementById("listing_preview");
    var sticky = product_preview.offsetTop;
    
    function myFunction() {
      if (window.pageYOffset > sticky +100) {
        product_preview.classList.add("sticky");
      } else {
        product_preview.classList.remove("sticky");
      }
    }



var originalBottom = 30; // get this depending on your circumstances
var footerHeight = $('.footer').height() // get this depending on your circumstances

$(window).scroll(function () { // start to scroll
  // calculating the distance from bottom
  var distanceToBottom = $(document).height() - $(window).height() - $(window).scrollTop();

  if (distanceToBottom <= footerHeight) // when reaching the footer
    $("#listing_preview").css('top', '-'+ (footerHeight - distanceToBottom) + 'px');
  else // when distancing from the footer
    $("#listing_preview").css('top',  originalBottom + 'px'); 
    // only need to specify 'px' (or other unit) if the number is not 0
});

</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM