smooth page scrolling w/ active link and offset
HTML
<nav>
<ul>
<li><a href="#about">about</a></li>
<li><a href="#services">services</a></li>
<li><a href="#contact">contact</a></li>
</ul>
</nav>
<div id="wrap">
<div id="about">about</div>
<div id="services">services</div>
<div id="contact">contact</div>
<div id="footer">footer</div>
</div>
CSS
* {width: 100%;}
body {margin:0; padding: 0;}
nav {position: fixed; background-color: gray;}
li {display: inline;}
.active {color: yellow}
#about {height: 500px; background-color: pink;}
#services {height: 500px; background-color: orange;}
#contact {height: 500px; background-color: purple;}
#footer {height: 500px; background-color: wheat;}
@media (max-width: 399px) {
nav {height: 50px;}
#wrap {padding-top: 50px;}
}
@media (min-width: 400px) {
nav {height: 100px;}
#wrap {padding-top: 100px;}
}
JavaScript
function getTargetTop(elem){
//gets the id of the section header
//from the navigation's href e.g. ("#html")
var id = elem.attr("href");
//Height of the navigation
var offset = $('nav').height();
//Gets the distance from the top and
//subtracts the height of the nav.
return $(id).offset().top - offset;
}
//Smooth scroll when user click link that starts with #
$('a[href^="#"]').click(function(event) {
//gets the distance from the top of the
//section refenced in the href.
var target = getTargetTop($(this));
//scrolls to that section.
$('html, body').animate({scrollTop:target}, 500);
//prevent the browser from jumping down to section.
event.preventDefault();
});
//Pulling sections from main nav.
var sections = $('a[href^="#"]');
// Go through each section to see if it's at the top.
// if it is add an active class
function checkSectionSelected(scrolledTo){
//How close the top has to be to the section.
var threshold = 30;
var i;
for (i = 0; i < sections.length; i++) {
//get next nav item
var section = $(sections[i]);
//get the distance from top
var target = getTargetTop(section);
//Check if section is at the top of the page.
if (scrolledTo > target - threshold && scrolledTo < target + threshold) {
//remove all selected elements
sections.removeClass("active");
//add current selected element.
section.addClass("active");
}
};
}
//Check if page is already scrolled to a section.
checkSectionSelected($(window).scrollTop());
$(window).scroll(function(e){
checkSectionSelected($(window).scrollTop())
});