Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add and remove Bootstrap navbar class depending on scroll position

I'm building a website, which begins with a static navbar after scrolling down (500px) the function removes the class "navbar-static-top" and adds "navbar-fixed-top". Which works correctly. But I want to make it change back to static when the user scroll back to the top.. I couldn't find anything about it online, ii've tried uses the jQuery 'hasClass()' function, but that doesn't work either...Any ideas?

This is what i have now..

   $(window).scroll(function() {
    $('#navbarMain').each(function(){
    var imagePos = $(this).offset().top;

    var topOfWindow = $(window).scrollTop();

        if (imagePos > topOfWindow-500) {
            $(this).removeClass("navbar-static-top");
            $(this).addClass("navbar-fixed-top");
        }

    });
}); 
like image 360
Egghead Avatar asked Oct 18 '25 13:10

Egghead


2 Answers

i'm using this

$(window).scroll(function() {
    var nav = $('#navbarMain');
    var top = 200;
    if ($(window).scrollTop() >= top) {

        nav.addClass('fixed');

    } else {
        nav.removeClass('fixed');
    }
});
like image 74
ciprian2301 Avatar answered Oct 20 '25 04:10

ciprian2301


var mainbottom = $('#navbarMain').offset().top + $('#navbarMain').height();

$(window).on('scroll',function(){ 
  stop = Math.round($(window).scrollTop()); 
  if (stop > mainbottom) { 
     $('.navbar-static-top').addClass('navbar-fixed-top'); 
  } else { 
     $('.navbar-static-top').removeClass('navbar-fixed-top'); 
  } 
});
like image 20
Kiran Avatar answered Oct 20 '25 03:10

Kiran