Javascript to hide header

Headroom.js

Give your pages some headroom. Hide your header until you need it.

Installation

Download here (sizes shown are after gzipping) :

npm install headroom.js --save yarn add headroom.js 

What’s it all about?

Headroom.js is a lightweight, high-performance JS widget (with no dependencies!) that allows you to react to the user’s scroll. The header on this site is a living example, it slides out of view when scrolling down and slides back in when scrolling up.

Why use it?

Fixed headers are a popular approach for keeping the primary navigation in close proximity to the user. This can reduce the effort required for a user to quickly navigate a site, but they are not without problems…

Large screens are usually landscape-oriented, meaning less vertical than horizontal space. A fixed header can therefore occupy a significant portion of the content area. Small screens are typically used in a portrait orientation. Whilst this results in more vertical space, because of the overall height of the screen, a meaningfully-sized header can still be quite imposing.

Headroom.js allows you to bring elements into view when appropriate, and give focus to your content the rest of the time.

How does it work?

In response to scroll events, headroom.js adds and removes CSS classes to an element:

Relying on CSS classes affords headroom.js great flexibility. The choice of what to do when scrolling up or down is now entirely yours — anything you can do with CSS you can do in response to the user’s scroll.

Usage

Headroom.js has a pure JS API, plus an optional jQuery plugin and AngularJS directive.

Include the headroom.js script in your page, and then:

// if you're using a bundler, first import: import Headroom from "headroom.js"; // grab an element var myElement = document.querySelector("header"); // construct an instance of Headroom, passing the element var headroom = new Headroom(myElement); // initialise headroom.init(); 

Options

Headroom.js can also accept an options object to alter the way it behaves. You can see the default options by inspecting Headroom.options . The full structure of an options object is as follows:

var options = < // vertical offset in px before element is first unpinned offset : 0, // or you can specify offset individually for up/down scroll offset: < up: 100, down: 50 >, // scroll tolerance in px before state changes tolerance : 0, // or you can specify tolerance individually for up/down scroll tolerance : < up : 5, down : 0 >, // css classes to apply classes : < // when element is initialised initial : "headroom", // when scrolling up pinned : "headroom--pinned", // when scrolling down unpinned : "headroom--unpinned", // when above offset top : "headroom--top", // when below offset notTop : "headroom--not-top", // when at bottom of scroll area bottom : "headroom--bottom", // when not at bottom of scroll area notBottom : "headroom--not-bottom", // when frozen method has been called frozen: "headroom--frozen", // multiple classes are also supported with a space-separated list pinned: "headroom--pinned foo bar" >, // element to listen to scroll events on, defaults to `window` scroller : someElement, // callback when pinned, `this` is headroom object onPin : function() <>, // callback when unpinned, `this` is headroom object onUnpin : function() <>, // callback when above offset, `this` is headroom object onTop : function() <>, // callback when below offset, `this` is headroom object onNotTop : function() <>, // callback when at bottom of page, `this` is headroom object onBottom : function() <>, // callback when moving away from bottom of page, `this` is headroom object onNotBottom : function() <> >; // pass options as the second argument to the constructor // supplied options are merged with defaults var headroom = new Headroom(element, options); 

CSS

Recall that headroom.js works by adding and removing CSS classes in response to the user’s scroll. This means you will need some CSS to achieve the effect you want. For example, you could hide the header on scroll down, and reveal it again on scroll up. The most basic CSS for this would be:

.headroom--pinned < display: block; >.headroom--unpinned

Whilst this is functional, it’s a bit of a jarring effect. We could do better with some CSS transitions to smoothly move the header in and out of view:

/** * Note: I have omitted any vendor-prefixes for clarity. * Adding them is left as an exercise for the reader. */ .headroom < will-change: transform; transition: transform 200ms linear; >.headroom--pinned < transform: translateY(0%); >.headroom--unpinned

Notice that we’re transitioning the transform property. The reason to transition this is because transforms are much cheaper to animate compared to top , bottom etc. Another benefit is that translation percentage values are relative to the dimensions of the element, whereas top etc. percentage values are relative to the dimensions of the viewport. This means you don’t need to know the height of the element in advance, -100% will always slide the element entirely out of view.

Читайте также:  Вставить текущую дату html

The CSS above is enough to get you started, but feel free to try something entirely different. Let you imagination run wild. But not too wild, your users won’t appreciate that.

Methods

The following methods are available to be called on a headroom instance:

  • destroy() : destroy the headroom instance, removing event listeners and any classes added
  • pin() : forcibly set the headroom instance’s state to pinned
  • unpin() : forcibly set the headroom instance’s state to unpinned
  • freeze() : freeze the headroom instance’s state (pinned or unpinned), and no longer respond to scroll events
  • unfreeze() : resume responding to scroll events

Clicking on anchor links (links within the same page) causes scrolling of the page. If this causes a scroll upwards, Headroom will pin the header. This can cause the linked element to be obscured by the header.

To avoid this problem we can define scroll-padding in CSS, which is designed for just this purpose:

Usage with jQuery

Include the headroom.js and jQuery.headroom.js scripts in your page, and then:

// simple as this! // NOTE: init() is implicitly called with the plugin $("#header").headroom(); // or with options $("#header").headroom(options); 

The plugin also offers a data-* API if you prefer a declarative approach.

Usage with AngularJS

Include the headroom.js and angular.headroom.js scripts in your page, and require the headroom module in your AngularJS application module. Then:

Examples

Head over to the headroom.js playroom if you want see some example uses. There you can tweak all of headroom’s options and try out various CSS effects in an interactive demo.

Читайте также:  Программа округления чисел python

Browser support

Headroom.js is dependent on the following browser APIs:

All of these APIs are capable of being polyfilled, so headroom.js can work with less-capable browsers if desired. Check the linked resources above to determine if you must polyfill to achieve your desired level of browser support.

If you do not want to polyfill each of the above APIs, you can test for browser support before initialising. This avoids errors in older browsers and treats headroom.js as a progressive enhancement:

Changelog

v0.12.0 (2020-10-16)

v0.11.0 (2020-01-16)

v0.10.4 (2020-01-09)

Источник

How to Hide/Reveal a Sticky Header on Scroll (With JavaScript)

In this tutorial we’ll learn how to hide the page header when scrolling down the page, then reveal it when scrolling up. As a bonus, we’ll also make the header menu fully functional.

Why Use Sticky Components?

Sticky components (such as headers) are extremely popular in the world of web design; they can keep essential UI elements permanently in view, and easily accessible should users need them. However, under certain circumstances (if the headers hold lots of content, or the viewport size and orientation limit the amount of available screen space) sticky headers can be obtrusive.

“When implemented wrong, sticky navigation elements can serve as a distraction from the actual content.” – Aaron Andre Chichioco

A sticky header that disappears from view when not needed (ie: when the user is scrolling to see more content) is an excellent compromise.

We can achieve this kind of effect by using an external library like Headroom.js, but we’re going to learn the mechanics of what’s underneath by building something ourselves. As a bonus, we’ll also make the header menu fully functional, ready for you to add your own customization.

What We’re Building

Here’s what we’re going to create (scroll to test the behavior):

1. Begin With the Page Markup

The markup will consist of the following elements:

  • A header that will contain a nav . Within it, we’ll put the menu toggle button and the menu itself.
  • A Lottie animation coming from the LottieFiles library. This will play each time we scroll down. Upon click, the menu will appear.
  • Just for enriching the page with some dummy content, we’ll also define three full-screen sections. We’ll add a few background images to them taken from a previous tutorial.
 width="20" height="20" viewBox="0 0 24 24"> 
 d="M24 10h-10v-10h-4v10h-10v4h10v10h4v-10h10z"/> 
 href="" role="button" aria-label="Toggle menu" class="lottie-wrapper"> 
 src="https://assets10.lottiefiles.com/datafiles/9gIwZ2uiiKglyb0/data.json" style="width: 60px; height: 60px;"> 

It’s worth mentioning that to make the Lottie animation clickable, we’ll wrap it around a link that will have role=»button» . Normally, we would wrap it around a button element. However, as lottie-player emits div s, it’s semantically incorrect to put a div inside a button .

2. Add the Sticky Header CSS

Let’s add some CSS rules to improve the way our header and animation look and (to a degree) behave.

For the sake of simplicity, I won’t walk through the initial reset styles, but feel free to look at them by clicking on the CSS tab of the demo project.

The header and animation styles are pretty straightforward, but two things have importance:

  1. Firstly, the toggle menu wrapper, the menu, and the Lottie animation will be fixed positioned elements.
  2. Secondly, the menu and Lottie animation will initially be hidden.

The related styles are as follows:

background: var(--lightpurple); 
.page-header .trigger-menu svg  
background: var(--lightpurple); 

The sections will behave as full-screen elements with a background image and a dark overlay on top of it. These will give us something to scroll past so we can see the hide/reveal behavior of our header:

background-repeat: no-repeat; 
background-position: center; 

3. Add the JavaScript

As a next step, let’s add some behavior to the menu.

Toggle Menu

Each time we click on the toggle button, the menu’s visibility will change. If it’s hidden, it’ll appear. But if it’s visible, it’ll disappear.

We’re handling this in quite a rudimentary way, but it gives you the potential to tailor things to your liking.

Here’s the required JavaScript code:

const triggerMenu = document.querySelector(".page-header .trigger-menu"); 
triggerMenu.addEventListener("click", () =>  
body.classList.toggle("menu-open"); 
.page-header .trigger-menu svg  

As you may have noticed, there isn’t any animation during the changes of the menu’s state. That happens because I used the non-animatable display property. If you want to add some kind of animation, replace this property with something animatable like opacity or visibility .

Toggle Header

Let’s now turn our attention to something more interesting.

Each time we scroll down, the toggle button (and the header in general) should disappear with a slide-out animation while the Lottie animation will start to play. If we then scroll up, it should appear with a slide-in animation while the Lottie animation will stop.

Note: for this tutorial, we’ll embed the Lottie animation using the LottieFiles web player. If you want to learn more about it, take some time to read this article. Anyway, this process is optional and beyond the main focus of this project.

To implement this functionality, we’ll use two helper classes: scroll-up and scroll-down . More specifically:

  • As we scroll down, the body will receive the scroll-down class.
  • As we scroll up, it’ll receive the scroll-up class.
  • If we scroll to the top of the page, it will lose its scroll-up class.

To detect the scrolling direction, we’ll store the last scroll position in a variable ( lastScroll ). Initially, the value of this variable will be 0. Then as we scroll, we’ll check if the new position is greater than or less than the old one. Based on the result of that condition, we’ll apply the corresponding class to the body .

Here’s the JavaScript code to handle that:

const nav = document.querySelector(".page-header nav"); 
const menu = document.querySelector(".page-header .menu"); 
const lottiePlayer = document.querySelector("lottie-player"); 
const scrollDown = "scroll-down"; 
window.addEventListener("scroll", () =>  
const currentScroll = window.pageYOffset; 
body.classList.remove(scrollUp); 
if (currentScroll > lastScroll && !body.classList.contains(scrollDown))  
body.classList.remove(scrollUp); 
body.classList.add(scrollDown); 
currentScroll  lastScroll && 
body.classList.contains(scrollDown) 

Источник

Оцените статью