Search code examples
javascriptjquerycsssticky

Unstick a fixed element based on page scroll


I have a calculator on my site (written in php), and in the end of this calculator there is a div with the results.

On desktop it works fine, but on mobile, i want to fix the results div to the bottom until scrolling the original position of the div. After that i want to change its position to static.

In other words, there is a fixed (to bottom) element on the page and after scrolling, at the original position of the div, i want to unstick it.

I hope, its understandable, but there is an example page - Look at the MOBILE version!!!

How can i do that?

Thanks in advance!


Solution

  • If you don't care about IE browsers (or if you're reading this in 2022 :D)
    you can use position: sticky

    .sticky{
      position: sticky;
      bottom: 0;
      background: red;
    }
    <div class="content">
      <p style="border:4px dashed;height:150vh;">Scroll down</p>
      <div class="sticky">I'M STICKY</div>
    </div>
    
    <div class="content">
      <p style="border:4px dashed;height:150vh;">Scroll up</p>
    </div>

    https://caniuse.com/#feat=css-sticky

    If you want a (kind-of?) fallback you could:

    .sticky{
      position: absolute; /* fallback to absolute */
      width: 100%;        /* fallback width */
      position: sticky;
      bottom: 0;
      background: red;
    }