Sticky Footer and Hidden Header on Scroll with jQuery

A well-designed website not only presents valuable content but also ensures a smooth and intuitive user experience. In this article, we’ll delve into a jQuery code snippet that enhances user experience by implementing two useful features: a sticky footer that stays at the bottom of the page and a hidden header that disappears when scrolling down.

The Code

jQuery(document).ready(function ($) {
  let oldValue1 = 0;
  let newValue1 = 0;
  window.addEventListener('scroll', (e) => {
    var distance = $('footer').offset().top;
    newValue1 = window.pageYOffset;
    if (distance <= newValue1) {
      jQuery("header").addClass("header_hide");
      $('header').css('opacity', '0');
    } else {
    jQuery("header").removeClass("header_hide");
    $('header').css('opacity', '1');
    }
  });
});

How It Works

Let’s break down the code to understand how these features are implemented.

  1. Sticky FooterThe code begins by initializing two variables, oldValue1 and newValue1, which are used to track the scrolling position.

    When the user scrolls, the window object’s scroll event listener is triggered. The code calculates the distance of the footer from the top of the page using $('footer').offset().top and updates the newValue1 with the current scrolling position using window.pageYOffset.

    If the distance of the footer from the top is less than or equal to the current scrolling position (distance <= newValue1), the code adds a class "header_hide" to the header element and sets its opacity to 0, effectively hiding the header. Otherwise, if the user is scrolling back up, the class is removed, and the header becomes visible again.

  2. Hidden Header on ScrollThe hidden header on scroll adds a layer of sophistication to the design, making more room for the content and improving the readability of the page.

Why It Matters

  1. Improved Readability: By hiding the header when scrolling down, the content becomes more prominent, allowing users to focus on what matters most.
  2. Sticky Footer: The sticky footer ensures that important information or actions are always accessible, even on long pages.
  3. Enhanced User Experience: These features contribute to a seamless and visually pleasing user experience, making navigation more enjoyable.

Conclusion

Incorporating a sticky footer and a hidden header on scroll using jQuery can greatly enhance the user experience on your website. These features provide a clean and uncluttered interface, making it easier for users to engage with your content. When designing your website, remember that small touches like these can go a long way in ensuring user satisfaction and engagement.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.