I am trying to implement a script that adds the class navbar-fixed-top to the navigation when the user scrolls. Here is the code I have so far:
var nav;
function yScroll(){
nav = document.getElementById('nav');
yPos = window.pageYOffset;
if(yPos > 150){
nav.className = nav.className + " navbar-fixed-top";
} else {
nav.className = nav.className - " navbar-fixed-top";
}
}
window.addEventListener("scroll", yScroll);
However, I am encountering an issue where the script keeps adding the navbar-fixed-top class every time yPos is greater than 150. This results in multiple instances of the same class being added as I scroll up and down.
Is there a way to ensure that the class is only added once, or do you have any alternative solutions? I have two navigations and I only want both of them to be fixed after the user has scrolled, hiding the top one from view.