ArticleZip > Jquery Sticky Header That Shrinks When Scrolling Down

Jquery Sticky Header That Shrinks When Scrolling Down

Having a sticky header on your website can enhance user experience by ensuring important navigation stays visible as visitors scroll down the page. Pairing this feature with a shrinking effect adds a touch of elegance to your site design. In this guide, we'll show you how to create a jQuery sticky header that shrinks when scrolling down, providing a seamless and visually appealing element for your website.

To achieve this effect, we'll utilize jQuery along with some CSS to handle the styling aspects. Let's dive into the steps to implement this feature on your website.

Step 1: HTML Markup
First, ensure that your header structure is properly set up in the HTML code. You'll have a container element for the header itself and another wrapping element for the page content below.

Html

<header id="header">
   <!-- Your header content goes here -->
</header>

<div id="content">
   <!-- Page content goes here -->
</div>

Step 2: CSS Styling
Next, let's define the initial styles for the header and the content container. The header will retain its initial size and appearance.

Css

#header {
   background-color: #333;
   color: #fff;
   height: 80px; /* Initial height of the header */
   position: fixed;
   width: 100%;
   z-index: 1000;
   transition: all 0.3s; /* Adding smooth transition effect */
}

#content {
   margin-top: 80px; /* Allot space for the fixed header */
   /* Other styles for your content container */
}

Step 3: jQuery Implementation
Now, let's add the jQuery script to handle the scrolling and shrinking effect of the header. We'll detect the scroll position and adjust the header size accordingly.

Javascript

$(document).ready(function() {
   var header = $('#header');
   var startScroll = 0;

   $(window).scroll(function() {
      var currentScroll = $(this).scrollTop();

      if (currentScroll &gt; startScroll) {
         header.addClass('hide');
      } else {
         header.removeClass('hide');
      }

      startScroll = currentScroll;
   });
});

Step 4: Additional CSS for Shrinking Effect
To ensure the shrinking effect, we'll add a CSS class that reduces the height of the header when the scrolling direction is downward.

Css

#header.hide {
   height: 50px; /* Shrinking height for the header */
   /* Additional styles for the shrunk header */
}

By following these steps and customizing the styles to match your website's design, you can implement a jQuery sticky header that shrinks elegantly as users scroll down. This feature not only improves usability but also adds a polished touch to your site's overall appearance. Experiment with different styling options and make this effect uniquely yours!

×