Make Header/Navigation Change Colour When On Different Section Of The Website
I am working on a website redesign for my personal portfolio website. I had a cool feature in mind where my header/navigation bar would change colour depending on what section of t
Solution 1:
JQuery's offset and scrollTop functions should do the trick. .offset() gets the current coordinates of the element, while .scrollTop() will get the current scrollbar position. Compare them and change CSS when conditions are met. See example:
var top1 = $('#home').offset().top;
var top2 = $('#featuredWork').offset().top;
var top3 = $('#caseStudy').offset().top;
$(document).scroll(function() {
var scrollPos = $(document).scrollTop();
if (scrollPos >= top1 && scrollPos < top2) {
$('#change').css('background-color', '#f00');
} else if (scrollPos >= top2 && scrollPos < top3) {
$('#change').css('background-color', '#0f0');
} else if (scrollPos >= top3) {
$('#change').css('background-color', '#00f');
}
});
body {
margin: 0;
padding-top: 30px
}
header {
position: fixed;
top: 0;
width: 100%;
height: 30px;
background-color: #000;
}
section {
height: 500px;
background-color: #aaa;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header id="change">
<div class="container">
<nav>
<a href="#home">Welcome</a>
<a href="#featuredWork">Work</a>
<a href="#caseStudy">Case Study</a>
</nav>
</div>
</header>
<section id="home">Content</section>
<section id="featuredWork">Content</section>
<section id="caseStudy">Content</section>
Post a Comment for "Make Header/Navigation Change Colour When On Different Section Of The Website"