Animated Sticky Header

Animated Sticky Header

If you want to add an animated sticky header to your website, there are a few ways you can do it using HTML, CSS, and JavaScript. One of the easiest ways is to use jQuery to add a class to your header when the user scrolls down the page.

Step 1: Add jQuery

Before you can use jQuery, you need to add it to your HTML file. You can either download the jQuery library and include it in your project or use a CDN:

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

Step 2: Add CSS

You can add some CSS to make your header sticky and animate it when the user scrolls down:

.header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,.1);
  transform: translateY(-100%);
  transition: transform .3s ease-in-out;
}

.header.sticky {
  transform: translateY(0);
}

The position: fixed; property makes the header stay at the top of the screen even when the user scrolls down. The transform: translateY(-100%); property hides the header above the screen, and the transition: transform .3s ease-in-out; property animates the header when it appears.

Step 3: Add JavaScript

You can use jQuery to add a class to your header when the user scrolls down:

$(window).on('scroll', function() {
  if ($(window).scrollTop() > 50) {
    $('.header').addClass('sticky');
  } else {
    $('.header').removeClass('sticky');
  }
});

The $(window).on('scroll', function() { ... }); code listens for the user scrolling the page. The $(window).scrollTop() function returns how many pixels the user has scrolled down. If the user has scrolled down more than 50 pixels, the .header element gets a sticky class added to it. If the user scrolls back up above 50 pixels, the .header element gets the sticky class removed from it.

You can also use CSS to animate the header using the @keyframes rule:

@keyframes slide-down {
  from {
    transform: translateY(-100%);
  }
  to {
    transform: translateY(0);
  }
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,.1);
  animation: slide-down .3s ease-in-out;
}

.header.sticky {
  animation: none;
}

The @keyframes slide-down { ... } code defines an animation that slides the header down from above the screen. The .header element gets an animation property that uses the slide-down animation. When the header is sticky, it gets an animation: none; property to prevent it from animating again.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe