jQuery on scroll toggle between two classes

14,378

Solution 1

Using toggleClass() may be the wrong solution for this. Use addClass/removeClass instead:

if ($(window).scrollTop() > 100){
    $('.navigation').addClass( "blue");
}
else {
    $('.navigation').removeClass("blue");
}

Solution 2

Try the following code:

$(document).ready(function () {
    $(window).scroll(function () {
        $('.navigation').toggleClass("blue", ($(window).scrollTop() > 100));
     });
});

Here's the example in jsbin

Solution 3

You can use .addClass() and removeClass()like this one: http://jsfiddle.net/csdtesting/qhfmw8hx/

$(window).scroll(function() {
  var windowYmax = 100;
  var scrolledY = $(window).scrollTop();

  if (scrolledY > windowYmax) {

    $('.navigation').addClass("blue");
  } else {
    $('.navigation').removeClass("blue");
    $('.navigation').addClass("red");
  }
});
.navigation {
  height: 800px;
}
.navigation.red {
  background: red;
}
.navigation.blue {
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navigation red">scroll me down and up please to see me changing colors...</div>

Hope it helps!

Share:
14,378

Related videos on Youtube

agis
Author by

agis

Updated on September 15, 2022

Comments

  • agis
    agis over 1 year

    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 ?

  • Lbatson
    Lbatson over 9 years
    This of course works because .blue is declared later in the css, however if it was reversed then it wouldn't. I would recommend explicitly removing classes you don't want and adding those you do to prevent that type of issue
  • Control Freak
    Control Freak over 9 years
    It should be enough to infer from.