Site icon Puneet Sharma – Freelance Web Developer

Sticky Sidebar

Javascript function to make the sidebar sticky to the bottom if the content length is more than the sidebar. Also, check the demo for the same.

DEMO

See the Pen Sticky Sidebar by Puneet Sharma (@webdevpuneet) on CodePen.

JavaScript

let vw = Math.max(document.documentElement.clientWidth);
let vh = Math.max(document.documentElement.clientHeight);

// Sticky sidebar scripts
if (vw > 1200){
  let scroller = document.getElementsByClassName("sticky-sidebar-scroller")[0];
  let sidebar = document.getElementsByClassName("sticky-sidebar")[0];
  let sidebarWrapper = document.getElementsByClassName("sticky-sidebar-wrapper")[0];
  let sidebarContent = document.getElementsByClassName("sticky-sidebar-content")[0];
  let scrollerInner = document.getElementsByClassName("sticky-sidebar-scroller-content")[0];
  sidebar.style.top = scroller.offsetTop + 'px';
  setTimeout(() => {
    sidebar.style.width = sidebarWrapper.offsetWidth + 'px';
    scrollerInner.style.minHeight = sidebarContent.offsetHeight + 50 + 'px';
    // let sidebar_content = document.getElementsByClassName("sticky-sidebar-content")[0];
    scroller.addEventListener("scroll", function() {
      let scrollTop = scroller.scrollTop; // current scroll position
      sidebar.scrollTop = scrollTop;
    });
  }, "100");
}

Exit mobile version