Create Animated Resizing Header On Scroll with Javascript

Category: Navigation | July 12, 2018
Author: Nick
Official Page: Go to Website
Last Update:August 1, 2023
License:MIT

Learn how to create animated resizing header on scroll with the help of  CSS3 & Javascript. It’s a fixed header which uses the transition property.

Before implementing the animation on the header, it’s also important to design a colorful animated header to make your site look more attractive.

When the user scrolls down the page, the header will shrink and the inner elements will adjust their size by using the transition CSS element.

We included the basic element in the header. It has a logo on the left side and few menu links on the right side of the header.

All of the elements on the header will shrink and resize to make them smaller when scrolling the page down.

To make this header work, we have to use the latest CSS3 animation and a few lines of javascript. The header gives you a nice looking effect while scrolling

How to Animated Resizing Header On Scroll

It is very easy to implement. You have to call two lines of script in the head.

<link rel="stylesheet" href="resizeheader.css" />
<script src="classie.js"></script>

After that, you need to define the basic structure of HTML. Let’s start with the header element then add a container. Next, place the logo inside the H1 tag.

By using the nav element we can easily define the menu links.

<header>
    <div class="container clearfix">
        <h1 id="logo">
            LOGO
        </h1>
        <nav>
            <a href="">Lorem</a>
            <a href="">Ipsum</a>
            <a href="">Dolor</a>
        </nav>
    </div>
</header>

Finally, add the following Javascript. The script will add the different class when a user scrolls to the specific part. The function will add an additional class smaller when a user scrolls and reach to the specific point which we set in the function.

<script>
function init() {
	window.addEventListener('scroll', function(e){
		var distanceY = window.pageYOffset || document.documentElement.scrollTop,
			shrinkOn = 300,
			header = document.querySelector("header");
		if (distanceY > shrinkOn) {
			classie.add(header,"smaller");
		} else {
			if (classie.has(header,"smaller")) {
				classie.remove(header,"smaller");
			}
		}
	});
}
window.onload = init();
</script>