How to Create a Sticky Sidebar with jQuery on Scroll?

Estimated read time 2 min read

Sure! Here’s an example of how you can create a sticky sidebar using jQuery on scroll:

HTML:

<!DOCTYPE html>
<html>
<head>
  <title>Sticky Sidebar Example</title>
  <style>
    .container {
      width: 100%;
      display: flex;
    }

    .sidebar {
      width: 25%;
      background-color: lightgray;
      padding: 16px;
      position: sticky;
      top: 0;
      height: 100vh; /* Adjust to the desired height */
    }

    .content {
      width: 75%;
      padding: 16px;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="sidebar">
      <!-- Sidebar content goes here -->
      <p>Sticky Sidebar</p>
    </div>
    <div class="content">
      <!-- Main content goes here -->
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sagittis euismod arcu, et ultricies purus suscipit eu. Nam semper neque in facilisis ullamcorper. Integer facilisis, odio a venenatis malesuada, justo tellus bibendum lacus, vitae dignissim purus lacus non libero. Praesent et varius libero. Ut aliquet lorem ut vehicula. Cras eget malesuada ex. Nam sit amet enim ut erat elementum venenatis. Nulla semper augue nec facilisis.</p>
    </div>
  </div>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
      $(window).scroll(function() {
        var sidebar = $(".sidebar");
        var sidebarTop = sidebar.offset().top;
        var scrollTop = $(window).scrollTop();

        if (scrollTop > sidebarTop) {
          sidebar.addClass("sticky");
        } else {
          sidebar.removeClass("sticky");
        }
      });
    });
  </script>
</body>
</html>

CSS:

/* Add the following CSS to your stylesheet */
.sticky {
  position: fixed !important;
  top: 0;
}

This code creates a sticky sidebar that sticks to the top of the page when scrolling down, and un-sticks when scrolling back up. The position: sticky; CSS property is used to make the sidebar stick to the top of its parent container when it reaches the top of the viewport. The jQuery code listens for scroll events on the window, calculates the position of the sidebar, and adds/removes a sticky class to the sidebar element accordingly. The sticky class is defined in the CSS with position: fixed; to fix the position of the sidebar when it’s sticky.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply