Search code examples
javascriptjquerycssaddclassremoveclass

addClass and removeClass methods aren't working properly


I am planning to add and remove background-image to a specific DIV but it seems that it's not working well

jQuery code :

$(document).ready(function(){
 $(window).scroll(function(){
  if ($(this).scrollTop() > 340) {
   $("#navcontainer").addClass("bg2");
  } else {
   $("#navcontainer").addClass("bg1");
  }
 });
});

here is the css code :

#navcontainer{
height: 70px;
width: 100%;
position: fixed;
z-index: 9999;
}

.bg2{
background-image: url(bg2.png);
}
.bg1{
background-image:url(bg1.png);
}

Solution

  • addClass and removeClass accepts one or more classNames without the period

    $("#navcontainer").addClass("bg2");
    

    It should be noted that jQuery has a toggleClass as well

    $(window).scroll(function(){
        $("#navcontainer").toggleClass('bg2', $(this).scrollTop() > 340);
    });