PapT
PapT

Reputation: 623

Change navbar background color after scrolling

My navbar has a transparent background, and I wanted to add a different bg when a user scrolls down.

I used the code from this question: Changing nav-bar color after scrolling?

my code now looks like this:

$(document).ready(function(){
var scroll_start = 0;
var startchange = $('#startchange');
var offset = startchange.offset();
if (startchange.length){
    $(document).scroll(function() {
        scroll_start = $(this).scrollTop();
        if(scroll_start > offset.top) {
            $(".navbar-fixed-top").css({'background-color':'#24363d',
                                        'opacity': '0.3'});
        } else {
            $('.navbar-fixed-top').css({'background-color':'transparent'});
        }
    });
}
});

When I scroll down, everything works ok, the bg and the opacity applies, but when I scroll back to the top this style is still there. I want it to change back to the default styling with no background.

Thanks

Upvotes: 1

Views: 9621

Answers (3)

Malik Umer
Malik Umer

Reputation: 64

try this one

          <script>
$(document).ready(function(){
  $(window).scroll(function(){
    var scroll = $(window).scrollTop();
      if (scroll > 54) {
        $(".navbar-fixed-top").css("background" , "blue");
      }

      else{
          $(".navbar-fixed-top").css("background" , "white");   
      }
  })
})
      </script>

Upvotes: 3

Shobhit Srivastava
Shobhit Srivastava

Reputation: 549

In the else part, you don't need the curly braces

$(document).ready(function(){
var scroll_start = 0;
var startchange = $('#startchange');
var offset = startchange.offset();
if (startchange.length){
    $(document).scroll(function() {
        scroll_start = $(this).scrollTop();
        if(scroll_start > offset.top) {
            $(".navbar-fixed-top").css({'background-color':'#24363d',
                                        'opacity': '0.3'});
        } else {
            $('.navbar-fixed-top').css('background-color':'transparent');
        }
    });
}
});

Upvotes: 1

Taniya
Taniya

Reputation: 550

It is better to add a new class when scroll down and remove that class when scroll up back. And add css on that new class.

    if(scroll_start > offset.top) {
        $(".navbar-fixed-top").addClass("fixednav");
    } else {
        $('.navbar-fixed-top').removeClass("fixednav");
    }

CSS:

  .navbar-fixed-top.fixednav{
        background:#24363d;
        opacity:0.3;
   }

Upvotes: 2

Related Questions