-1

I want remove .bg-light from nav element at 400px and more scrolls

<nav id="my-nav" class="bg-light navbar text-info"> change my background color</nav>

I know it's an easy task with jQuery but is it possible to do it with vanilla js?

Thanks for spending time on my question I will be glad to see opinion

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ilia0017
  • 5
  • 2
  • Do any of the [answers here](https://stackoverflow.com/questions/2481350/how-to-get-scrollbar-position-with-javascript) help? (Or try one of [these](https://flaviocopes.com/how-to-get-scroll-position-element/) [tutorials](https://www.geeksforgeeks.org/how-to-get-the-position-of-scrollbar-using-javascript/?ref=lbp).) – Cat Sep 06 '21 at 04:25

2 Answers2

0

First, we start by grabbing the "nav" element using the ID. Then setting our Y-axis's offset. Attach a listener to the window object. On scroll, compare the current position to our desired offset.

const navBar = document.getElementById("my-nav");

const offset = 400;

window.addEventListener("scroll", () => {
    if (window.scrollY >= offset){
        navBar.classList.remove("bg-light")
    } else {
        navBar.classList.add("bg-light")
    }
})
YMH
  • 121
  • 6
0

Yes, its possible with Vanilla JavaScript, use the "scroll" event handler to get the info. As the users moves through the site it will return the Y axis position in pixels. By using an if statement remove or add the bg-light class, like so:

let nav = document.getElementById("my-nav");

window.addEventListener("scroll", (e) => { 

  if(this.scrollY > 400){ nav.classList.remove('bg-light') }
  else{
    nav.classList.add('bg-light')
  }

});
*{padding:5px}
html{height:3000px;font-size:20px}
.bg-light{background-color: #F8F8F8!important; color:black!important;}
.navbar{position:fixed;background-color:blue; color:white;}
<nav id="my-nav" class="bg-light navbar text-info"> Change my background color at scrollY 400px</nav>
Gass
  • 7,536
  • 3
  • 37
  • 41