0

I'm trying to make JS code to change the navbar background to transparent on scroll but for some reason it's not working and I've tried console log and it's working so can you help me out to find what's wrong?

<script type="text/javascript">
$(document).scroll(function(){
    if($(this).scrollTop() > 1)
    {   
        $(".navbar-fixed-top").css("background-color", "white !important");
        console.log("Done");
    } else if ($(this).scrollTop() <= 1) {
        $(".navbar-fixed-top").css("background-color", "transparent !important");
        console.log("Back");
    }
});
</script>
  • Look in the computed styles in the dev tools. Where is the element getting its background color from? Is the correct one being set but you just cant see it? – ruby_newbie Jun 27 '18 at 14:05

1 Answers1

1

Your code is correct, but you can't defined a CSS attribute as !important by this way so just remove it

$(".navbar-fixed-top").css('background-color', 'white');`

Or use

$(".navbar-fixed-top").style('background-color', 'white', 'important');`

Check on this post How to apply !important using .css()?

Note : By the way try to save $(".navbar-fixed-top") somewhere to improve performance and avoid to fetch it each time you scroll the window

D. Schreier
  • 1,700
  • 1
  • 22
  • 34