Skip to content

Instantly share code, notes, and snippets.

@azborgonovo
Last active March 27, 2023 20:47
Show Gist options
  • Save azborgonovo/93a932a3f6989e11311e to your computer and use it in GitHub Desktop.
Save azborgonovo/93a932a3f6989e11311e to your computer and use it in GitHub Desktop.
Simple smart sticky navigation bar
<html>
<head>
<title>Simple Smart Sticky Navigation Bar</title>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
//Calculate the height of <header>
//Use outerHeight() instead of height() if have padding
var aboveHeight = $('header').outerHeight();
//when scroll
$(window).scroll(function(){
//if scrolled down more than the header’s height
if ($(window).scrollTop() > aboveHeight){
// if yes, add “fixed” class to the <nav>
// add padding top to the #content
// (value is same as the height of the nav)
$('nav').addClass('fixed').next().css('padding-top','60px');
} else {
// when scroll up or less than aboveHeight,
// remove the “fixed” class, and the padding-top
$('nav').removeClass('fixed').next().css('padding-top', '0');
}
});
});
</script>
<style type="text/css">
#wrapper {
width:940px;
margin: 0 auto;
}
header {
text-align:center;
padding:70px 0;
}
nav {
background:url(img/nav-bg.png) no-repeat;
height: 60px;
width: 960px;
margin-left: -10px;
line-height:50px;
position: relative;
}
nav.fixed {
top: 10;
}
#content {
background: #fff;
height: 1500px; /* presetting the height */
box-shadow: 0 0 5px rgba(0,0,0,0.3);
}
.fixed {
position:fixed;
}
</style>
</head>
<body>
<div id="wrapper">
<header>
<h1>Simple Smart Sticky Navigation Bar</h1>
</header>
<nav>
<p>Navigation Content</p>
</nav>
<div id="content">
<p>Website content here.</p>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment