Home > front end >  Dynamic bottom value based on element position in browser
Dynamic bottom value based on element position in browser

Time:08-19

I am attempting to adapt this JS solution to keep a floating element above the footer of my site.

The adaption I am attempting is instead of changing the element position to absolute, I would have a dynamic bottom px value based on the position of the top of the footer, relevant to the client window.

function checkOffset() {

  var onlineFloat = document.querySelector('#online-ceo');
  var footer = document.querySelector('.site-footer');

  function getRectTop(el){
    var rect = el.getBoundingClientRect();
    return rect.top;
  }
    
  if((getRectTop(onlineFloat)   document.body.scrollTop)   onlineFloat.offsetHeight >= (getRectTop(footer)   document.body.scrollTop) - 20)
        var newBottom = ((getRectTop(footer)   document.body.scrollTop) - 40).toString().concat('px');
    onlineFloat.style.bottom = newBottom;

  if(document.body.scrollTop   window.innerHeight < (getRectTop(footer)   document.body.scrollTop))
    onlineFloat.style.bottom = '20px';// restore when you scroll up
    
}

document.addEventListener("scroll", function(){
  checkOffset();
});

The output of newBottom is currently a px value which changes on scroll, however, I am having issues setting this position to the element.

Where am I going wrong? Thanks.

CodePudding user response:

With your approach (changing the bottom property), you can just calculate where the "float" should be if the footer's top position is in view (as in window.innerHeight) on scroll.

        function checkOffset() {
            var onlineFloat = document.querySelector('#online-ceo');
            var footer = document.querySelector('.site-footer');

            function getRectTop(el) {
                var rect = el.getBoundingClientRect();
                return rect.top;
            }
            var newBottom = 10   (getRectTop(footer) < window.innerHeight ? window.innerHeight - getRectTop(footer) : 0)   'px';

            onlineFloat.style.bottom = newBottom;
        }

        document.addEventListener("scroll", function () {
            checkOffset();
        });
  • Related