0

If I scroll down on my website my navigation bar will go from "background-color: transparent" to black, and if I scroll up again it turns transparent again.

var positionSmall = 0;
    $(document).scroll(function () {
        positionSmall = $(this).scrollTop();
        if (positionSmall > 140) {
            $(".navbar").css('background-color', '#222222');
        } else {
            $(".navbar").css('background-color', '');
        }
    });

This works, but I now want the background color to fade in when scrolled down, and fade out when scrolled up again. I've tried the .fadein and .animate functions from jquery, but they didn't seem to work for me. Does anyone have any ideas on how to do this?

Fabricator
  • 12,722
  • 2
  • 27
  • 40
Max
  • 357
  • 1
  • 6
  • 16
  • Making a background color fade in and out is a bit more difficult. I'd suggest using rgba to set the background color, which allows you to control the transparency: rgba(0, 0, 0, .50) would be 50% black, rgba(0, 0, 0, 1) would be 100% black, etc. See this answer: http://stackoverflow.com/a/14362680/870729 – random_user_name Dec 31 '15 at 21:12
  • Possible duplicate of [How can I animate the opacity of the background of a div?](http://stackoverflow.com/questions/16254943/how-can-i-animate-the-opacity-of-the-background-of-a-div) – random_user_name Dec 31 '15 at 21:13

1 Answers1

1

No need for jQuery, you can do this with CSS. Just add a transition to your .navbar class, it will animate the transition even if the change is made in jQuery.

Code:

.navbar {
    -webkit-transition: background-color 0.5s ease-in-out;
    -moz-transition: background-color 0.5s ease-in-out;
    -ms-transition: background-color 0.5s ease-in-out;
    -o-transition: background-color 0.5s ease-in-out;
    transition: background-color 0.5s ease-in-out;
}

Now you just have to modify the time and you should be good to go. Here is it in action.

Hunter Turner
  • 6,804
  • 11
  • 41
  • 56