willscode
willscode

Reputation: 96

position fixed at a given height

I have been trying to put an element to fixed position within a given scroll height with Javascript. Outside of this height range, the position should be back to relative.

Here is what I have done so far. The position:fixed is inside the about-option class. When it gets to 4680, the class is added.

How do I make it have a height end-point of 5800 i.e 4680 - 5800, and also remove the class outside this height range?

window.onscroll = function () {
        myFunction();
      };

      function myFunction() {
        if (
          document.documentElement.scrollTop > 4680 ||
          document.body.scrollTop > 4680
        ) {
          document.getElementById("about-txt").classList.add("about-option");
        } else {
          document.getElementById("about-text").className = "";
        }
      }

css

.about-option {
  position: fixed;
  top: 20%;
  width: 40%;
  right: 7%;

Upvotes: 1

Views: 790

Answers (1)

luh
luh

Reputation: 41

I guess you are trying to do what position sticky does: once the element hits the window's top boundery it starts sticking and if you scroll to the inverse way, it goes back to move together with content. Like here:

https://codepen.io/elad2412/pen/QYLEdK

<main class="main-container">
  <header class="main-header">HEADER</header>
  <div class="main-content">MAIN CONTENT</div>
  <footer class="main-footer">FOOTER</footer>
</main>
body{color:#fff; font-family:arial; font-weight:bold; font-size:40px; }
.main-container{ max-width:600px; margin:0 auto; border:solid 10px green; padding:10px; margin-top:40px;}
.main-container *{padding:10px;background:#aaa; border:dashed 5px #000;}
.main-container * + *{margin-top:20px;}
.main-header{
  height:50px; background:#aaa; border-color:red;
}
.main-content{
  min-height:1000px;
}

.main-header{position:-webkit-sticky; position:sticky; top:0;}

The trick part is to remember to add a container outside the sticky element, otherwise, it will not work.

I hope it helps!

Upvotes: 1

Related Questions