Search code examples
jqueryhtmlcsssticky

How to stick div at bottom of page when it has completely entered the viewport?


What I try to achieve is the following:

I have a div anywhere on my page. I would like to fix this div at the bottom of the page when it has completely entered the viewport.

What I have tried so far:

// section.js

(function ($) {
    'use strict';

     $(function () {
         var sections = $('.js-section');

         sections.each(function () {
             var section = $(this);
             var sticky = section.hasClass('js-section-sticky');

             if (sticky) {
                 $(window).bind('scroll', function() {
                     var windowTop = $(window).scrollTop();
                     var sectionTop = section.offset().top - section.height() - windowTop;

                     if (windowTop > sectionTop) {
                         section.addClass('section--fixed-bottom');
                     }
                     else {
                        section.removeClass('section--fixed-bottom');
                     }
                 });
              }
         });
     });
})(window.jQuery);

However, currently the section appears too early. It appears immediately and not when it has completely entered the viewport. Additionally, if I scroll up it disappears too late.


Solution

  • replace your code with my below code

    (function ($) {
        'use strict';
    
         $(function () {
             var sections = $('.js-section');
    
             sections.each(function () {
                 var section = $(this);
                 var sticky = section.hasClass('js-section-sticky');
                 var sectionTop = section.offset().top + section.height();
                 if (sticky) {
                     $(window).bind('scroll', function() {
                         var windowTop = $(window).scrollTop()+$(window).height();
    
                         if (windowTop > sectionTop) {
                             section.addClass('section--fixed-bottom');
                             section.next().css("margin-top", section.next().css("margin-top").replace("px", "") + section.height());
                         }
                         else {
                            section.removeClass('section--fixed-bottom');
                            var marginTop = section.next().css("margin-top").replace("px", "") - section.height();
                            if(marginTop < 0) 
                               marginTop*(-1);
                            section.next().css("margin-top", marginTop);
                         }
                     });
                  }
             });
         });
    })(window.jQuery);
    

    It will work fine