Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addClass removeClass not working

My first time asking question here. I searched through questions but I couldn't find similar problems.

I'm building a corporate website with bootstrap3 on Brackets. I check to see if things work on latest version of chrome and safari.

I'm trying to make my navbar shrink its height and change background color using JQuery addClass and removeClass, but it seems to be not working at all. When I change CSS property via JQuery, it works. I can change the background color. So I tried to change multiple CSS properties via Jquery, it wouldn't work. It only allows me to change background color.

$(document).ready(function() {
  $(window).scroll(function() {
    if ($(window).scrollTop() > 50) {
      $("#top-bar").addClass('animated-header');
    } else {
      $("#top-bar").removeClass('animated-header');
    }
  });

  $("#clients-logo").owlCarousel({
    itemsCustom: false,
    pagination: false,
    items: 5,
    autoplay: true,
  })

}); //this is the part doesn't work

$(document).ready(function() {
  $(window).scroll(function() {
    if ($(window).scrollTop() > 50) {
      $("#top-bar").css("background-color", "#ef7c7c");
    } else {
      $("#top-bar").css("background-color", "transparent");
    }
  });

  $("#clients-logo").owlCarousel({
    itemsCustom: false,
    pagination: false,
    items: 5,
    autoplay: true,
  })
}); //this part works perfectly
#top-bar {
  background: transparent;
  color: #fff;
  -webkit-transition: all 0.2s ease-out 0s;
  transition: all 0.2s ease-out 0s;
  padding: 30px 0;
  height: 15%;
}
#top-bar .animated-header {
  /*Background Color of nav bar when scrolled*/
  background-color: #ef7c7c;
  padding: 10px 0;
  height: 10%;
  -webkit-box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.1);
  box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.1);
}
<header id="top-bar" class="navbar-fixed-top animated-header">
  <div class="container">

Thank you very much for your help!

like image 324
Reiko Kawahara Avatar asked Dec 06 '22 17:12

Reiko Kawahara


1 Answers

The problem isn't in the JS using .addClass(), the problem is that the selector in your CSS is wrong. This:

#top-bar .animated-header {

Should be this:

#top-bar.animated-header {

That is, remove the space before the . because with the space the selector is matching elements with class animated-header that are descendants of #top-bar. Without the space it matches the #top-bar element itself if it also has the animated-header class.

like image 182
nnnnnn Avatar answered Dec 30 '22 03:12

nnnnnn