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 ?
The problem is that you call toggleClass everytime the user scrolls. This code would fix this issue:
The jsbin
Using
toggleClass()
may be the wrong solution for this. UseaddClass
/removeClass
instead:Try the following code:
Here's the example in jsbin
You can use
.addClass()
andremoveClass()
like this one: http://jsfiddle.net/csdtesting/qhfmw8hx/Hope it helps!
You're working with adding a class and removing another, i would suggest just using addClass and removeClass for this case. Also you can chain the methods.
Here's the jsbin