Coder
Coder

Reputation: 1139

Using jQuery to change rgba background color when user scrolls

I have a navbar in which I would like the rgba background color to be changed when the user scrolls down, I would also like it to return to its original rgba color when the user scrolls back to the top of the screen. I am trying to use .animate as I would like the background change to ease in and out, however the .animate function does not seem to do anything at all and there are no errors on the console??

I cannot seem to find a clear and clean answer on this, so any help/advice would be great.

$(document).ready(function(){
    var scroll_pos = 0;
        $(document).scroll(function() { 
            scroll_pos = $(this).scrollTop();
            if(scroll_pos > 50) {
                $(".navbar").animate({'background-color': 'rgba(255, 255, 255, 0.5)'}, 3000);
            } else {
                $(".navbar").animate({'background-color': 'rgba(0, 0, 0, 0)'}, 3000);
            }
        });
});

Upvotes: 0

Views: 331

Answers (1)

Virtual
Virtual

Reputation: 131

Don't use animation. Set a transition via CSS to the navbar like this

.navbar { transition: background-color 1s; }

And change via JS the backgroundcolor

$(document).ready(function(){
    //var scroll_pos = 0; // you don't need this
        $(document).scroll(function() { 
            //scroll_pos = $(this).scrollTop();
            if(scroll_pos > $(this).scrollTop()) {
                $(".navbar").css('background-color', 'rgba(255, 255, 255, 0.5)');
            } else {
                $(".navbar").css('background-color', 'rgba(0, 0, 0, 0)');
            }
        });
});

Upvotes: 1

Related Questions