Search code examples
javascriptcssnavigationnavsticky

Sticky position of nav change background at scroll position


I want the <nav> to be fixed with the 3 numbers. When it reaches the green square, it should go OVER the numbers and stay fixed and turn red. And when you go back to the top, it should go back to it's original position and go back to green. How would I achieve this?

.container {
  height: 1000px;
}

nav{
  display: flex;
  justify-content: space-around;
}

.square{
  background-color: green;
  width: 100px;
  height: 100px;
  margin: auto;
  display: block;
  position: sticky;
}
<div class="container">
  <header>
    <nav>
      <p>1</p>
      <p>2</p>
      <p>3</p>
    </nav>
  </header>
  <div class="square"></div>
</div>


Solution

  • you can use javascript to detect scroll and use window.onscroll to add sticky class to your element, also note that when using sticky CSS attribute value for display you should also adjust the location, I used calc to calculate the left value, here is a working snippet:

    window.onscroll = function() {myFunction()};
    
    var header = document.querySelector(".square");
    var sticky = header.offsetTop;
    
    function myFunction() {
      if (window.pageYOffset > sticky) {
        header.classList.add("sticky");
      } else {
        header.classList.remove("sticky");
      }
    }
    .container {
      height: 10000px;
    }
    
    nav {
      display: flex;
      justify-content: space-around;
    }
    
    .square {
      background-color: green;
      width: 100px;
      height: 100px;
      margin: auto;
      display: block;
    }
    
    .sticky {
      position: fixed;
      top: 0;
      background-color:red;
      left: calc((100% - 100px)/2);
    }
    
    .sticky + .content {
      padding-top: 102px;
    }
    <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
    
    <div class="container">
      <header>
        <nav>
          <p>1</p>
          <p>2</p>
          <p>3</p>
        </nav>
      </header>
    
    
      <div class="square"></div>
    
    </div>
    </body>
    </html>