DEV Community

Cover image for Sticky Sidebar in Vanilla JavaScript
Dhruvang Gajjar
Dhruvang Gajjar

Posted on

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

Top comments (0)