Mountain Spring Mountain Spring - 4 months ago 59
Javascript Question

Bootstrap navbar collapse on scroll

I'm using bootstrap grayscale theme for my project and It has a navbar that collapses on scroll, or if I go to a link that's on the same page (#download etc.)

The problem is when I go to anchor link from some other page, than navbar doesn't collapse until I scroll.

I guess the solution is in adding the line in java script, but I really don't know what to add since I don't know java. :-(

// jQuery to collapse the navbar on scroll
$(window).scroll(function() {
if ($(".navbar").offset().top > 50) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});


Please, help. :) :-*

Answer

You need to run the check when the page loads as well as when the window is scrolled, you can do that without duplicating any code by putting the logic that checks the offset of the page in a function and running it from both document ready and window scroll.

$(document).ready(function() {

    // Put your offset checking in a function
    function checkOffset() {
        if ($(".navbar").offset().top > 50) {
            $(".navbar-fixed-top").addClass("top-nav-collapse");
        }     
        else {
            $(".navbar-fixed-top").removeClass("top-nav-collapse");
        }
    }

    // Run it when the page loads
    checkOffset();


    // Run function when scrolling
    $(window).scroll(function() {
        checkOffset();
    });
});