iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🙌

Show/Hide Header on Scroll Template | HTML, CSS(SCSS), JS

に公開
2024/09/20

Overview

A template for a header that toggles visibility on scroll. When scrolling down, the header disappears at the top of the screen; when scrolling back up, it reappears from the top.
I use this frequently, so I've made it into a template.
Sample Page

Prerequisites

File structure

/
├ logo-256x512.png
├ index.html
├ style.css
└ script.js

Code

HTML / index.html

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sample</title>
  <link rel="stylesheet" href="./style.css">
  <script src="./script.js"></script>
</head>
<body>
<!-- Start from here -->
  <header>
    <div class="header-wrap">
        <div class="header-logo">
            <a href="#">
                <img src="./logo-256x512.png" alt="Sample Header Logo Image" />
            </a>
        </div>
        <div class="header-menu">
            <nav>
                <li><a href="#">Menu 1</a></li>
                <li><a href="#">Menu 2</a></li>
            </nav>
        </div>
    </div>
  </header>
<!-- Up to here is required -->
</body>
</html>

CSS / style.css

style.css
* {
  margin: 0;
  padding: 0;
  box-sizing: content-box;
}

header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: black;
  height: 50px;
}
header * {
  transition: 0.4s;
}
header li, header a {
  list-style: none;
  color: white;
  text-decoration: none;
}
header.hide {
  animation: headerFadeOut 1s;
  opacity: 0;
}
header.show {
  opacity: 1;
  animation: headerFadeIn 1s;
}

.header-wrap {
  height: 100%;
  display: flex;
}

.header-logo, .header-logo * {
  height: 100%;
}
.header-logo a {
  display: flex;
  align-items: center;
  text-align: center;
}
.header-logo a:hover {
  opacity: 0.6;
}

.header-menu {
  flex-grow: 10;
  display: flex;
  justify-content: space-between;
}
.header-menu nav {
  display: flex;
}
.header-menu li {
  display: flex;
  align-items: center;
  margin: 0 0.5rem;
}
.header-menu a:hover {
  opacity: 0.6;
}

@keyframes headerFadeOut {
  0% {
    opacity: 1;
    top: 0;
  }
  100% {
    opacity: 0;
    top: -100%;
  }
}
@keyframes headerFadeIn {
  0% {
    top: -100%;
  }
  100% {
    top: 0;
  }
}/*# sourceMappingURL=style.css.map */

Converted from SCSS. The source code is as follows:

SCSS Source Code
style.scss
@charset "UTF-8";

// Time taken for the header show/hide animation
$HEADER-ANIMATION-DURATION: 1s;
// Header height
$HEADER-HEIGHT: 50px;

* {
    margin: 0;
    padding: 0;
    box-sizing: content-box;
}

header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    background-color: black;
    height: $HEADER-HEIGHT;
    * {
        transition: .4s;
    }

    li, a {
        list-style: none;
        color: white;
        text-decoration: none;
    }
    
    &.hide {
        animation: headerFadeOut $HEADER-ANIMATION-DURATION;
        opacity: 0;
    }
    &.show {
        opacity: 1;
        animation: headerFadeIn $HEADER-ANIMATION-DURATION;
    }
}

.header-wrap {
    height: 100%;
    display: flex;
}

.header-logo {
    &, * {
        height: 100%;
    }
    a {
        display: flex;
        align-items: center;
        text-align: center;
        &:hover {
            opacity: .6;
        }
    }
}

.header-menu {
    flex-grow: 10;
    display: flex;
    justify-content: space-between;

    nav {
        display: flex;
    }
    li {
        display: flex;
        align-items: center;
        margin: 0 .5rem;
    }
    a {
        &:hover {
            opacity: .6;
        }
    }
}

@keyframes headerFadeOut {
    0% {
      opacity: 1;
      top: 0;
    }
    100% {
      opacity: 0;
      top: -100%;
    }
}

@keyframes headerFadeIn {
    0% {
        top: -100%;
    }
    100% {
        top: 0;
    }
}

JS / script.js

script.js
const CONSTS = {
    /** 
     * Time taken for the header show/hide animation
     * Specify the same duration as HEADER-ANIMATION-DURATION in style.scss
     * @type {Number} Unit: milliseconds
     */
    HEADER_ANIMATION_DURATION: 1000,
    /**
     * Header height
     * Specify the same height as HEADER-HEIGHT in style.scss
     * @type {Number} Unit: px
     */
    HEADER_HEIGHT: 50,
}

/**
 * Called on scroll
 * @param {Number} scrolled Height from the top of the page when scrolled
 * @param {Number} previousScroll The previous scrolled value
 */
function onScroll(scrolled, previousScroll) {
    const hd = document.querySelector('header');

    // When scroll amount is less than header height: The header is not fixed to the screen
    if (scrolled <= CONSTS.HEADER_HEIGHT) {
        if (hd.style.position !== 'absolute') hd.style.position = 'absolute';
        if (hd.style.top !== '0') hd.style.top = '0';
    }
    // When scrolling down: Hide the header
    else if (scrolled > previousScroll) {
        if (hd.classList.contains('show')) hd.classList.remove('show');
        if (!hd.classList.contains('hide')) hd.classList.add('hide');
    }
    // When scrolling back up: Show the header
    else {
        // Reset styles applied to the element
        hd.style.top = '';
        hd.style.position = '';
        
        if (hd.classList.contains('hide')) hd.classList.remove('hide');
        if (!hd.classList.contains('show')) hd.classList.add('show');
    }
}

// Executed once the DOM content is loaded
document.addEventListener('DOMContentLoaded', () => {
    // Execute onScroll function during scroll
    let previousScroll = 0;
    let scrolled = 0;
    window.addEventListener("scroll", async () => {
        previousScroll = scrolled;
        scrolled = window.pageYOffset
        onScroll(scrolled, previousScroll);
    });
});

Points to Note

There are parts where common values should be set in both CSS and JS. However, since the CSS in this template is converted from SCSS, please edit the SCSS and convert it again when setting those values.
Points to set:

  • JS HEADER_ANIMATION_DURATION and SCSS $HEADER-ANIMATION-DURATION
  • JS HEADER_HEIGHT and SCSS $HEADER-HEIGHT

Also, when creating content, please note that the header element's position will be absolute or fixed. Content may go under or behind the header element. Adjustments are required as appropriate.

Discussion