Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto hide Angular Material toolbar (top navigation bar) on scroll down

I currently have an Angular app that uses standard toolbar as the top navigation. picture of top part of my web app

Now I would like the navigation bar to scroll up with the user when they scroll down and reappear when they scroll up.

I've tried using window.pageYOffset but as mentioned here, this value always returns 0.

I've made a Stackblitz with my current setup for my navbar here.

like image 997
Job Avatar asked Oct 17 '22 05:10

Job


1 Answers

The no-JS way

You can do the trick only using CSS. This will hide the navbar progressively as soon as you start scrolling.

.exemple-toolbar {
  position: sticky;
  top: -200px;
  padding-top: 200px;
  height: 250px;
}

The onScroll way

Set a scroll listener on your container div, and add a class to the navbar depending on the scroll direction.

scrollTop = 0;
hideNav = false;

onScroll(event) {
  this.hideNav = this.scrollTop < event.target.scrollTop;
  this.scrollTop = event.target.scrollTop;
}
.container {
  height: 100vh;
  overflow-y: scroll;
  overflow-x: hidden;
}

.nav {
  position: fixed;
  height: 50px;
  display: flex;
}

.nav.hide-nav {
  display: none; /* You can play on opacity for nice transitions*/
}
<div class="container" (scroll)="onScroll($event)">

  <div class="nav" [class.hide-nav]="hideNav">
     <!-- Nav -->
  </div>

<!--content-->

</div>

This can work with an HostListener as well, but the parent node of your component has to be scrollable (which is not the case in your example)

like image 122
Alex Avatar answered Oct 21 '22 01:10

Alex