Skip to content Skip to sidebar Skip to footer

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');
  } elseif (scrollPos >= top2 && scrollPos < top3) {
    $('#change').css('background-color', '#0f0');
  } elseif (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;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><headerid="change"><divclass="container"><nav><ahref="#home">Welcome</a><ahref="#featuredWork">Work</a><ahref="#caseStudy">Case Study</a></nav></div></header><sectionid="home">Content</section><sectionid="featuredWork">Content</section><sectionid="caseStudy">Content</section>

Post a Comment for "Make Header/navigation Change Colour When On Different Section Of The Website"