Active Navigation Links on Scroll
This code adds the class "active" to the <a> tags with the class "link" when the element with the same ID as the HREF value is reached.
HTML
<header>
<nav>
<ul>
<li><a class="link active" href="#section_one">Section One</a>
</li>
<li><a class="link" href="#section_two">Section Two</a>
</li>
<li><a class="link" href="#section_three">Section Three</a>
</li>
</ul>
</nav>
</header>
<section id="section_one"></section>
<section id="section_two"></section>
<section id="section_three"></section>
CSS
/* RESET CSS */
* {
margin: 0;
padding: 0;
border: 0;
font-family: Calibri;
font-size: 100%;
vertical-align: top;
box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
}
/* MY STYLES */
html, body {
height: 100%
}
header {
background: #CCCCCC;
position: fixed;
left: 0px;
top: 0px;
height: 40px;
width: 100%
}
nav {
text-align: center;
}
nav ul {
display: inline-block;
text-align: center;
}
nav ul li {
float: left;
line-height: 40px;
list-style-type: none;
padding: 0px 10px;
}
nav ul li a {
color: #999999;
text-decoration: none;
}
nav ul li a.active {
color: #222222;
text-decoration: underline;
}
section {
min-height: 100%;
width: 100%;
}
#section_one {
background: #BBBBBB;
padding-top: 40px;
}
#section_two {
background: #999999;
}
#section_three {
background: #777777;
}
JavaScript
// ADDS ACTIVE CLASS TO LINKS WHEN SECTION WITH THE SAME SELECTOR AS THE HREF IS REACHED (CLASS .LINK IS NEEDED ON ALL <a> TAGS)
$(document).ready(function () {
$(window).scroll(function () {
var y = $(this).scrollTop();
$('.link').each(function (event) {
if (y >= $($(this).attr('href')).offset().top - 40) {
$('.link').not(this).removeClass('active');
$(this).addClass('active');
}
});
});
});
// SMOOTH SCROLLING (with negative scroll of 40 for header)
/* $(function () {
$('a[href*=#]:not([href=#])').click(function () {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: (target.offset().top - 40)
}, 850);
return false;
}
}
});
}); */