Background color ease on scroll

Viewed 18
<script>
  window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 10 || document.documentElement.scrollTop > 10) {
    document.getElementsById("bg-custom").style.backgroundColor = "#ede9e000";
  } else {
    document.getElementById("bg-custom").style.backgroundColor = "#ede9e0";
  }
}
</script>
<nav class="navbar navbar-expand-lg bg-custom sticky-top" id="bg-custom">

Hello guys I have this little part of my code where I want to ease the backgroundcolor on scroll. The color already changes on scroll, but how can I fix that is eases nice? If anyone can help me I would appreciate it a lot!

1 Answers

One method is to add a transition property in the CSS styling for #bg-custom. This will allow any properties that are changed to ease from the starting state/value into the value newly set through JavaScript.

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

function scrollFunction() {

  if (document.body.scrollTop > 10) {
    document.getElementsById("bg-custom").style.backgroundColor = "red";
  } else {
    document.getElementById("bg-custom").style.backgroundColor = "blue";
  }
}
.bg-custom {
  position: absolute;
  background-color: red;
  height: 50vh;
  width: 100vw;
  transition: 2s;
  z-index: 2;
}

div {
  position: absolute;
  height: 200vh;
  width: 100vw;
}
<nav class="navbar navbar-expand-lg bg-custom sticky-top" id="bg-custom">


  <div></div>

Related