Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Sticky header that shrinks when scrolling down

I wonder how to make a sticky header shrink(with animation) when you scroll down the page and goes back to normal state when the page is scrolled up to the top. Here are two examples to clearify:

http://themenectar.com/demo/salient/

http://www.kriesi.at/themes/enfold/

I get the part to make it fixed, but how should I do to shrink my header when the user scrolls down?

Thanks a ton

like image 633
user2362529 Avatar asked May 08 '13 13:05

user2362529


People also ask

How do I fix a scrolling header?

The answer I found was to add a spacer div above the element that will become fixed (nav element in my case), and set it to the same height as the nav element, and set it to display none. When adding the . fixed class to the nav, show the .


2 Answers

This should be what you are looking for using jQuery.

$(function(){   $('#header_nav').data('size','big'); });  $(window).scroll(function(){   if($(document).scrollTop() > 0) {     if($('#header_nav').data('size') == 'big')     {         $('#header_nav').data('size','small');         $('#header_nav').stop().animate({             height:'40px'         },600);     } } else   {     if($('#header_nav').data('size') == 'small')       {         $('#header_nav').data('size','big');         $('#header_nav').stop().animate({             height:'100px'         },600);       }     } }); 

Demonstration: http://jsfiddle.net/jezzipin/JJ8Jc/

like image 93
jezzipin Avatar answered Oct 18 '22 02:10

jezzipin


Here a CSS animation fork of jezzipin's Solution, to seperate code from styling.

JS:

$(window).on("scroll touchmove", function () {   $('#header_nav').toggleClass('tiny', $(document).scrollTop() > 0); }); 

CSS:

.header {   width:100%;   height:100px;   background: #26b;   color: #fff;   position:fixed;   top:0;   left:0;   transition: height 500ms, background 500ms; } .header.tiny {   height:40px;   background: #aaa; } 

http://jsfiddle.net/sinky/S8Fnq/

On scroll/touchmove the css class "tiny" is set to "#header_nav" if "$(document).scrollTop()" is greater than 0.

CSS transition attribute animates the "height" and "background" attribute nicely.

like image 20
Sinky Avatar answered Oct 18 '22 03:10

Sinky