Fixed site header when scrolling page


For a landing page or a site whose main page is loaded with content, sometimes you need to fixed the site header when scrolling the page. There are two ways to do this. Create a separate header, which we will fix, or remake the current header with styles.

In both cases, you need to write a jQuery script that will determine whether we have flipped through the site and the header has already disappeared, and make the necessary manipulations with it

var head=$('.header'); /* We put in a variable header */
var bottom=head.position().top + head.outerHeight(true); /* Determine the position at which the heading will be completely hidden after scrolling */

if($(window).scrollTop()>bottom){ /* If the open page is already scrolled below the site header */
	/* If a separate menu is created, which we fix, then we display it */
	$('.fixed-header').show();
	/* If we use the existing menu, then we add a class on which styles will be written */
	$('.header').addClass('scrolled');
}else{
	/* If you create a separate menu that we fix, then hide it */
	$('.fixed-header').hide();
	/* If we use the existing menu, then delete the class of the docked menu */
	$('.header').removeClass('scrolled');
}

$(window).resize(function(){ /* If we change the resolution of the browser, recount the position at which the header will be completely hidden  */
	bottom=head.position().top + head.outerHeight(true);
});

$(window).scroll(function(){
	if($(window).scrollTop()>bottom){ /* If header disappeared while scrolling */
		/* If a separate menu is created, which we fix, then we display it */
		$('.fixed-header').show();
		/* If we use the existing menu, then we add a class on which styles will be written */
		$('.header').addClass('scrolled');
	}else{
		/* If you create a separate menu that we fix, then hide it */
		$('.fixed-header').hide();
		/* If we use the existing menu, then delete the class of the docked menu */
		$('.header').removeClass('scrolled');
	}
});

If you fixed the current header, you can create such a class with styles

.scrolled{
	position:fixed;
	top: 0;
	left: 0;
	z-index: 999;
	-webkit-box-shadow: 0 1px 5px 0 rgba(0,0,0,0.1);
    -moz-box-shadow: 0 1px 5px 0 rgba(0,0,0,0.1);
    box-shadow: 0 1px 5px 0 rgba(0,0,0,0.1);
}



Connect

If you have any questions, want to get individual advice or you have an interesting offer, you can contact via the feedback form.

Or write to the email info@bobreod.ru





By submitting the form, you agree to our privacy policy