Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing navbar color on scroll after 100vh

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;
    
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading