Reputation: 1811
I am making a webpage which has anchor button on the top linking to different divs on the webpage, I want to change the background color of the button when the scroll is on that div and keep that color until it reaches the subsequent section.How can i use toggleClass in this ?
Upvotes: 0
Views: 1197
Reputation: 7766
Try this. The active link has green background.
$(window).scroll(function(){
var oneH = $('#one').offset().top;
var twoH = $('#two').offset().top;
if ($(window).scrollTop() >= oneH){
$("header a").removeClass("active");
$("header a#aone").addClass("active");
}
if ($(window).scrollTop() >= twoH){
$("header a").removeClass("active");
$("header a#atwo").addClass("active");
}
});
.sect{
width:100%;
height:600px;
background-color:yellow;
}
#two{
background-color:blue;
}
header{
position:fixed;
top:0;
}
header a{
display:inline-block;
width:50px;
border:1px solid black;
text-align:center;
background-color:red;
}
header a.active{
background-color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<a id="aone" class="active">div1</a>
<a id="atwo">div2</a>
</header>
<div class="sect" id="one"></div>
<div class="sect" id="two"></div>
Upvotes: 1