Button fixed to page when scrolling in mobile view with Javascript

2.1k Views Asked by At

hoping to get some JS/CSS help here. I need to have the checkout button on a page of mine go to the top of the page and become fixed if the user can no longer see it scrolling down the page in mobile view. I'm hoping someone can help! The one thing messing me up is that I can't use jQuery

![function checkoutScroll() {
    var button = document.querySelector('.cartSidebar__checkoutButton');
    window.addEventListener('scroll', function () {
      var distanceFromTop = document.body.scrollTop;
      if (distanceFromTop === 0) {
        button.style.position = 'static';
        button.style.top = 'auto';
      }
      if (distanceFromTop > 0) {
        button.style.position = 'fixed';
        button.style.top = '0px';
      }
    });
  }
2

There are 2 best solutions below

0
On

What you are trying to achieve can be done through CSS which would make more sense as it's a visual / UI task. I would add top margin equivalent to the css height of your button and leave it as fixed top. As a benefit, you would be able to take advantage of the media queries to limit the CSS rules to the mobile view.

@media screen and (max-width: 960px) {

    .container{
        margin: 3em;
    }

    .checkout_button{
        display:block;
        position:fixed;
        top:0;
        left:0;
        width:100%;
    }
}

something very simple like https://jsfiddle.net/f19Lus43/

If you want to stay in javascript for some obscure reasons ( I can't say compatibility because of document.querySelector is working only on evolved browser ) it's up to you but having an example of your code would help us respond :)

1
On

So I take it you want the function to only run on smaller screens/browser viewports? Is that what you mean by "mobile view"? I've been using this for a while. Not sure if its better than Glen's solution but it's worked for me without fault. First we define our functions:

function updateViewportDimensions() {
    var w=window,d=document,e=d.documentElement,g=d.getElementsByTagName('body')[0],x=w.innerWidth||e.clientWidth||g.clientWidth,y=w.innerHeight||e.clientHeight||g.clientHeight;
    return { width:x,height:y };
}
// setting the viewport width
var viewport = updateViewportDimensions();

function detectMob() {
  viewport = updateViewportDimensions();
  if (viewport.width <= 768) {
    return true;
  } else {
   return false;
  }
}

Then every time you need to check if the size of the viewport is less than 768 pixels wide you do:

if (detectMob){
  //your code here
}