Simple on-scroll animated header jQuery
Fixed header that changes its height when the page is scrolled
View the working demo here
There are times when you need a header fixed to the page, so that when the page is scrolled header stays at its location. Sometimes, the height of the header is long on first page load. An animated header will change its size on scroll. Once a certain amount of the page gets scrolled, the header will decrease its size and the inner elements will adjust their size. The following will demonstrate a simple header element with one <h1> tag in it.
HTML
<div class=”header”>
<h1>Animated Fixed Header (Scroll Down)</h1>
</div>
<div class=”content”>
</div>
The HTML is very simple. It contains a div of class header with one <h1> element. There is another div of class content which would basically contain the content of the page. To make the scroll appear on the page, I would the content div a height of 2000px.
CSS
.header {
position: fixed;
top: 0;
left: 0;
width: 100%;
background: #cc5350;
color:#fff;
z-index: 1000;
height: 200px;
overflow: hidden;
-webkit-transition: height 0.3s;
-moz-transition: height 0.3s;
transition: height 0.3s;
text-align:center;
line-height:160px;}
.header.shrink {
height: 100px;
line-height:80px;
}
.header h1
{
font-size:30px;
font-weight:normal;
-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
transition: all 0.3s;
}.header.shrink h1
{
font-size:24px;
-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
transition: all 0.3s;
}
.content
{
height:2000px;
/*just to get the page to scroll*/
}
jQuery
$(function(){
var shrinkHeader = 300;
$(window).scroll(function() {
var scroll = getCurrentScroll();
if ( scroll >= shrinkHeader ) {
$(‘.header’).addClass(‘shrink’);
}
else {
$(‘.header’).removeClass(‘shrink’);
}
});
function getCurrentScroll() {
return window.pageYOffset;
}
});
Line 2: sets the variable which defines when to change the height of the header
Line 3: Function runs when the window is scrolled
Line4: runs a function getCurrentScroll() which returns the current scroll value.
Line5: if the current window scroll value is greater than 300, the header is assigned a class shrink,which reduces its height and also changes the font size of the h1 (this is set up in the css above).