Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. :) :-*

like image 490
Mountain Spring Avatar asked Dec 29 '25 05:12

Mountain Spring


2 Answers

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

Edit:

I believe you could shorten this even more by replace the checkOffset function with the following:

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

I haven't tested this, but as long as the second parameter in toggleClass returns a boolean it'll either add or remove the class depending on the offset of the page without needing an if statement.

like image 111
Tim Sheehan Avatar answered Dec 30 '25 19:12

Tim Sheehan


You can also use :

 $(document).ready(function() {
        function checkOffset() {
            $(".navbar").removeClass("show");
        }
        // Run function when scrolling
        $(window).scroll(function() {
            checkOffset();
        });
        // Run function on Clicking
        $(window).click(function() {
            checkOffset();
        });
    });

This will help with navbar collapse on mobile devices.

like image 29
K_3 Avatar answered Dec 30 '25 18:12

K_3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!