2

I want to change the background-color of my navbar when position: sticky activates during scrolling.

I have managed to change the background-color of the navbar when the scroll arrives on it, but I would like to animate it to make this change more gradual.

This is what I tried:

window.onscroll = function() {myFunction()};

var navbar = document.getElementById("menu_navbar");

var rect = navbar.getBoundingClientRect();

function myFunction() {
  if (window.pageYOffset >= rect.top) {
     $( "#menu_navbar" ).animate({
        "background-color": "rgba(255, 229, 57, 0.8)"
     }, 1000);
  } 
  else {
     navbar.style.backgroundColor = 'transparent';
  }
}
Run_Script
  • 2,487
  • 2
  • 15
  • 30
Meds
  • 111
  • 1
  • 7

1 Answers1

5

You could simply declare a transition style:

transition: background-color .5s ease;

Then, whenever you change the background colour, it will animate.

T. Short
  • 3,481
  • 14
  • 30