Dan
Dan

Reputation: 13

Animate height change

The following code makes my navbar smaller on scroll and bigger when scrolling back to top: The original height is 15vh and the smallnav height is 8vh

$(document).ready(function($){
    var nav = $('nav');

    $(window).scroll(function () {
        if ($(this).scrollTop() > 13.35) {
            nav.addClass("smallnav");
        } else if($(this).scrollTop() > 0) {
            nav.removeClass("smallnav");
        }
    });
});

Now it just jumps from small to big or the other way around but how can I create an animation for this so that it shrinks or expands?

Upvotes: 1

Views: 64

Answers (2)

You can add the following to make a better flow in your change of the height:

  -webkit-transition: all 0.5s ease;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  transition: all 0.5s ease;

Demo

$(document).ready(function($) {
  var nav = $('nav');

  $(window).scroll(function() {
    if ($(this).scrollTop() > 13.35) {
      nav.addClass("smallnav");
    } else if ($(this).scrollTop() >= 0) {
      nav.removeClass("smallnav");
    }
  });
});
nav {
  height: 15vh;
  border: 1px solid black;
  position: fixed;
  top: 0;
  width: 100%;
  -webkit-transition: all 0.5s ease;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  transition: all 0.5s ease;
}

.smallnav {
  height: 8vh;
}

body {
  height: 200vh
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>your nav </nav>

Upvotes: 5

void
void

Reputation: 36703

Use this in your nav css

  -webkit-transition: height 1s; 
  -moz-transition: height 1s; 
  -ms-transition: height 1s; 
  -o-transition: height 1s; 
  transition: height 1s; 

And it will animate the height change over 1s.

Read more about this here.

Upvotes: 1

Related Questions