Sticky Sidebar in Vanilla JavaScript

dhruvangg

Dhruvang Gajjar

Posted on March 11, 2021

Sticky Sidebar in Vanilla JavaScript

This code is built with Pure JavaScript without any dependencies. It just count top and bottom edges of the element in which the element needs to be sticky.

You can also check the Demo

function offset(elt) {
  var rect = elt.getBoundingClientRect(), bodyElt = document.body;
  return {
    top: rect.top + bodyElt .scrollTop,
    left: rect.left + bodyElt .scrollLeft
  }
}

window.addEventListener("load", function(){
  if(document.querySelector("#sidebar")){
    const sidebar = document.querySelector("#sidebar");
    const footer = document.querySelector("section");
    const top = offset(sidebar).top;
    const footTop = offset(footer).top;
    const maxY = footTop - sidebar.offsetHeight

    window.addEventListener("scroll", function(){
      let y = document.scrollingElement.scrollTop;
      if (y > top) {
        if (y < maxY) {
          sidebar.classList.add("fixed")
          sidebar.removeAttribute('style');
        } else {
          sidebar.classList.remove("fixed")
          sidebar.setAttribute('style', 'position: absolute; top: '+(maxY - top)+'px');
        }
      } else {
        sidebar.classList.remove("fixed")
      }
    })
  }
});
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
dhruvangg
Dhruvang Gajjar

Posted on March 11, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related