6 ตุลาคม 2566

Changing nav-bar color after scrolling with JavaScript

JavaScript code:

const navbar = document.querySelector('.nav-fixed');
window.onscroll = () => {
    if (window.scrollY > 300) {
        navbar.classList.add('nav-active');
    } else {
        navbar.classList.remove('nav-active');
    }
};

CSS:

header.nav-fixed {
    width: 100%;
    position: fixed;
    transition: 0.3s ease-in-out;
}
.nav-active {
    background-color:#fff;
    box-shadow: 5px -1px 12px -5px grey;
}

Source: https://stackoverflow.com/questions/23706003/changing-nav-bar-color-after-scrolling