Reputation: 6626
Till now I have managed to do till this point--
After a certain pixel from page top the div changes it's background color.
But I want to change the background-color of that div only when it is being scrolled. Once the div has been scrolled past I want to change it's background color back to previous one.
This is the code that I have tried
$(window).scroll(function(){
if($(window).scrollTop()>50){
$('.q_ans_sec').attr('id', 'scrolled_fixedDiv');
} else {
$('.q_ans_sec').removeAttr('id');
}
});
.container-fluid {
background-color:blue;
height:500px;
}
#scrolled_fixedDiv.container-fluid {
background-color: red;
}
.nxtdiv {
height:500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="container-fluid q_ans_sec">
</div>
<div class="nxtdiv">
</div>
As you can see in the above example when you scroll up it is still red and changes its color to blue only when the scroll is less than 50px.
I want it to be blue when I scroll up again. Any idea how to achieve it.
Thanks!
Upvotes: 0
Views: 269
Reputation: 3294
Try this:
if($(window).scrollTop() > $(document).height()*0.5)
Try to retrieve the page height using $(document).height()
. If you want the viewport height, then you will need to use $(window).height()
.
Upvotes: 1