Issue
I am struggling to make the nav class .navbar change background-color on scroll down. I've used this code and some others, it's not working no matter what I try to implement. I am trying to get the nav to add the alt-color class after the view has left the top of the page
jQuery(document).ready(function($) {
$(window).scroll(function() {
var scrollPos = $(window).scrollTop(),
navbar = $('.navbar');
if (scrollPos > 10) {
navbar.addClass('alt-color');
} else {
navbar.removeClass('alt-color');
}
});
});
.navbar {
transition: 0.2s all linear;
background-color: #212121;
height: 100px;
width: 100%;
}
.navbar.alt-color {
background-color: #fff !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="navbar">
</nav>
Solution
As already said, you do not need to use jQuery. JQuery becomes more and more outdated and vanilla JS can do this as easy.
Simply add an Event Listener to the window: window.addEventListener
and check for the scroll
event.
Then you can add the class there based on a condition with classList.toggle
. Toggle allows for a second parameter as condition. In this case: this.scrollY > 10
window.addEventListener('scroll', function() {
const NAVBAR = document.querySelector('nav');
NAVBAR.classList.toggle('alt-color', this.scrollY > 10);
})
.navbar {
transition: 0.2s all linear;
background-color: #212121;
height: 100px;
width: 100%;
}
.navbar.alt-color {
background-color: blue;
}
/* added for demo purpose */
body {
min-height: 800vh;
}
nav {
position: sticky;
top: 0;
}
<nav class="navbar"></nav>
Answered By - tacoshy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.