title: Fix an element when it reaches the top of the screen using javascript and css
body: <p>I have an element, that I wish to stick on top after it reaches the top of the screen.</p>
  
  <pre><code>&lt;div id="HeaderWrapper"&gt;
    ...
    &lt;div id="Navigation"&gt;
      Navigation
    &lt;/div&gt;
    ...
  &lt;/div&gt;
  </code></pre>
  
  <p>I am adding an event listener on <code>scroll</code>, which would call a function to check the posting of the element by using <code>getBoundingClientRect()</code> method. If the <code>top</code> or the <code>y</code> of the element is less then 0 relative to the viewport, then I would like to fix/stick the header. Again if its more than 0 then I would like to remove the fix position. In both the cases, I am adding and removing a class name of <code>fixed_navbar</code> which has the property of fix position.</p>
  
  <pre><code>document.addEventListener("scroll", function() {
    const el = document.getElementById("Navigation");
    let rect = el.getBoundingClientRect();
    if (rect.top &lt;= 0) {
      el.classList.add("fixed_navbar");
    } else {
      el.classList.remove("fixed_navbar");
    }
  });
  </code></pre>
  
  <p>You can also the check the <a href="https://codepen.io/KakarN/pen/dVgzNb?editors=0010" rel="nofollow noreferrer">codepen demo</a>.</p>
  
  <p>When the position top of the element is more than zero it works fine. Also when scrolling down to the position where the element's top position is less than 0 it sticks to the page and has the fixed propery. But again when scrolling back to the position when the element's top is more than 0, the element still has the fixed propery and stick's to the top of the screen. How can I make the element stick to the top when it reaches the top of the screen and again when the element is below the top of the screen remove the fixed postion?</p>