By default I have a navigation bar which has a red background color.
What I want to do is when the users scrolls down more than 100px to change the background to blue and if he goes back to 0px to change the background to it's default state.
I want to do this by toggling between two classes, for example <div class="navigation red"> should be the default class and if the user scroll down to add <div class="navigation blue"> and if he scrolls back to have <div class="navigation red"> again.
Here is my attempt :
$(document).ready(function(){
$(window).scroll(function(){
if ($(window).scrollTop() > 100){
$('.navigation').toggleClass( "blue");
}
});
});
But this is not working. Here's a jsbin.
Any ideas how to get it to work ?
Try the following code:
$(document).ready(function () {
$(window).scroll(function () {
$('.navigation').toggleClass("blue", ($(window).scrollTop() > 100));
});
});
Here's the example in jsbin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With