Akhin Abraham
Akhin Abraham

Reputation: 74

How to shrink navbar vertically when scrolled down?

Here's the css of the navbar before it shrinks:

.navbar{
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    position: fixed;
    width: 100%;
    height: 15vh;
    background-color: transparent;
    z-index: 1;
    transition: 0.6s ease;
}

Here's what I want after it shrinks: (after scrolling down a bit)

.navbar.adjust{
    background-color: ivory;
    height: 10vh;
}

Help me out with the javascript part.

Upvotes: 1

Views: 99

Answers (2)

s.kuznetsov
s.kuznetsov

Reputation: 15223

Here is the solution you need. And this is a javascript solution.

The toggle() method is used here.

Class adjust rules are applied immediately on the first scroll.

window.onscroll = function() {
  let navbar = document.querySelector('.navbar');
    navbar.classList.toggle('adjust', this.scrollY > 0);
};
.main {
    height: 5000px;
}

.navbar{
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    position: fixed;
    width: 100%;
    height: 15vh;
    background-color: transparent;
    z-index: 1;
    transition: 0.6s ease;
}

.navbar.adjust{
    background-color: ivory;
    height: 10vh;
}
<div class="main">
  <ul class="navbar">
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
  </ul>
</div>

Upvotes: 1

Dung Le
Dung Le

Reputation: 96

var position = $(window).scrollTop();
  $(window).on("scroll", function () {
    var scroll = $(window).scrollTop();
    if (scroll > position) 
      //scroll down
      $(".navbar").addClass("adjust");   
 
    if (scroll == 0) 
      $(".navbar").removeClass("adjust"); 
    
    position = scroll;
  });
  //menu sticky
.navbar{
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    position: fixed;
    width: 100%;
    height: 15vh;
    background-color: transparent;
    z-index: 1;
    transition: all 0.6s ease;
}
.navbar.adjust{
    background-color: ivory;
    height: 10vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="navbar navbar-light bg-light">
  <span class="navbar-text">
    Navbar text with an inline element
  </span>
</nav>

<main style="min-height: 150vh;"></main>

Upvotes: 0

Related Questions