user4442171
user4442171

Reputation:

JavaScript add class once trough scroll

I want to add a class navbar-fixed-top to navigation when user scrolls i made this script:

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

But the problem is that it will always give a class to nav when yPos > 150.

So as i continue to scroll up and down in inspect element it adds a lot of same classes. How to add he class just once, or you have other solution. i have 2 navbar and i want just 2 to be fixed after user scrolled so he cant anymore see the top one.

Upvotes: 1

Views: 1901

Answers (2)

Bozidar Sikanjic
Bozidar Sikanjic

Reputation: 747

Check if it already has that class like this....

var nav;
function yScroll(){
    nav = document.getElementById('nav');
    yPos = window.pageYOffset;
    var isThereClass = nav.className.indexOf("navbar-fixed-top");
    if(yPos > 150 && isThereClass == -1){
        nav.className = nav.className + " navbar-fixed-top";
    } else if (yPos < 150 && isThereClass != -1) {
        nav.className = nav.className - " navbar-fixed-top";
    }
}
window.addEventListener("scroll", yScroll);

Upvotes: 1

Hugo Yates
Hugo Yates

Reputation: 2111

You're using jQuery so use:

nav.addClass("navbar-fixed-top")

and

nav.removeClass("navbar-fixed-top") 

I think this maybe what you want:

var nav;
function yScroll(){
    nav = $('#nav');
    yPos = window.pageYOffset;
    nav.removeClass("navbar-fixed-top");
    if(yPos > 150){
        nav.addClass("navbar-fixed-top");
    }
}
window.addEventListener("scroll", yScroll);

Upvotes: 2

Related Questions