Home > Enterprise >  Changing navbar color on scroll after 100vh
Changing navbar color on scroll after 100vh

Time:11-13

I want to change the color of my navbar when I scroll more than 100vh (when I changed from a section to another). How can I do that? I tested this code, but it doesn't work.

const myNav = document.getElementById('header');
window.onscroll = function () { 
    "use strict";
    if (document.body.scrollTop > document.height ) {
        myNav.classList.add("scrolled");
    } 
    else {;
        myNav.classList.remove("scrolled");
    }
};

This is the CSS:

header {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    transition: 0.2s;
    z-index: 1000;
    display: flex;
    justify-content: center;
}

.scrolled {
    background-color: black;
    z-index: 1;
    
}

CodePudding user response:

To get the scroll position use window.scrollY and to get the veiwport height use window.innerheight so do:

const myNav = document.getElementById('header')

window.onscroll = function() {
  if(window.scrollY > window.innerHeight){
    myNav.classList.add('scrolled')
  }else{
    myNav.classList.remove('scrolled')
  }
}
body{
  min-height: 400vh;
}

nav{
  position:fixed;
  top: 0;
  left: 0;
  height: 50px;
  width: 100%;
  background: green;
}

nav.scrolled{
  background: black;
}
<nav id="header"></nav>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related